在服务组件中使用setAlert函数时不起作用

时间:2019-02-27 09:33:50

标签: javascript angular typescript

我创建了一个名为alert的类,并在创建,删除或更改新帖子时使用它显示警报。 但是有一个问题,当我将setAlert放在DELETE / POST / PUT函数中时,如果后者位于服务组件中,则会给我一个错误,说:ERROR

但是当我将函数移到其component.ts文件中时,它可以正常工作而没有任何问题。那么为什么会发生这种情况,我该怎么做才能使其在服务中正常工作?

这是我的Alert.ts:

export class alert{
    "status" : boolean;
    "text": string;
    constructor(){
        this.status=false;
        this.text="";
    }
    public setAlert(text){
        this.status = true;
        this.text = text;
    }
    public close(){
        this.status = false;
    }
}

这是我的html文件:

<div class="forms container">
  <form #postForm="ngForm">
      <div class="form-group">
          <label for="title">Title</label>
          <input [(ngModel)]="formService.form.title"
          name="title"  
          id="title" 
          type="text" 
          class="form-control"
          >
      </div>
      <div class="form-group">
        <label for="body">Body</label>
        <textarea [(ngModel)]="formService.form.body" 
        name= "body" 
        id="body" 
        cols="30" 
        rows="10" 
        class="form-control"
        ></textarea>
      </div>
      <button class="btn btn-success" (click) = "formService.editForm()">Save</button>
      <button class="btn btn-danger pull-right" (click) = "formService.deleteForm()">Delete</button>

      <div class="container mt-4">
        <div class="row">
          <div class="col">
            <div *ngIf = "alert.status"  class="alert alert-success 
            alert-dismissible fade show" role="alert">
              <button type="button" class="close" data-dismiss="alert" aria-label="Close"
              (click) = "alert.close()">
                <span aria-hidden="true">&times;</span>
              </button>
              {{alert.text}}
            </div>
          </div>
        </div>
      </div>

    </form>
</div>

这是component.ts文件:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormService } from './forms.service';
import { HttpClient } from '@angular/common/http';
import { alert } from './alert';

@Component({
  selector: 'app-forms',
  templateUrl: './forms.component.html',
  styleUrls: ['./forms.component.css']
})


export class FormsComponent implements OnInit {

  alert: alert;
  id: any;
  posts: any;

  constructor(public formService: FormService ,private route: ActivatedRoute,
    private router: Router, private http: HttpClient) { }



  ngOnInit() {
    this.id=this.route.snapshot.params['id'];
    this.alert = new alert();

    this.posts = this.formService.getForms(this.id).subscribe(
      (forms: any) => {
        this.formService.form = forms[0];
      }
    );
  }

}

这是service.ts文件:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { form } from './form-interface';
import { alert } from './alert';


@Injectable({
    providedIn: 'root'
}) 

export class FormService {

  formsUrl = "https://jsonplaceholder.typicode.com/posts";
  form: form = {
      id: 0,
      userId: 0,
      title: '',
      body: ''
  };
  alert: alert;


    constructor(private http: HttpClient) { }

    ngOnInit() {
      this.alert = new alert();
    }

    getForms(id) {
            return this.http.get('https://jsonplaceholder.typicode.com/posts'
            + "?id=" + id)
    }

    editForm() {
        fetch(this.formsUrl + "/" + this.form.id, {
          method: 'PUT',
          body: JSON.stringify(this.form),
          headers: {
            "Content-type": "application/json; charset=UTF-8"
          }
        })
        .then(response => response.json())
        this.alert.setAlert("Post has been successfully saved !");
    }

    deleteForm() {
        this.http.delete(this.formsUrl + "/" + this.form.id)
        .subscribe(
          data  => {
            console.log("DELETE Request is successful ", data);
            this.alert.setAlert("Post has been successfully deleted !");

          },
          error  => {
            console.log("Error", error);
          }
        );
      }

}

1 个答案:

答案 0 :(得分:0)

服务没有生命周期public class UserConfiguration: IEntityTypeConfiguration<User> { public void Configure(EntityTypeBuilder<User> builder) { builder.HasKey(e => e.Id); builder.Property(e => e.Id) .HasColumnName("Id").ValueGeneratedOnAdd(); builder.Property(e => e.Email).HasMaxLength(250); builder.Property(e => e.Password).HasMaxLength(250); builder.Property(e => e.FirstName).HasMaxLength(100); builder.Property(e => e.LastName).HasMaxLength(100); builder.Property(e => e.CountryCode).HasDefaultValue(CountryCode.Unknown); // other configurations } } ,请将代码从ngOnInit更改为ngOnInit

constructor

只有组件和指令具有生命周期挂钩:

  

组件的生命周期由Angular本身管理。 Angular创建它,>渲染它,创建并渲染它的子对象,当它的数据绑定属性更改时检查它,并在从DOM中删除它之前销毁它。

     

指令和组件实例具有生命周期,而Angular会创建,更新和销毁它们。