如何使用EventEmitter在Angular中发出警报?

时间:2019-02-25 12:06:37

标签: angular typescript

我正在创建Angular应用程序,我想发出警报。我将在发送POST / PUT / DELETE请求并且希望显示一些成功消息的情况下使用它们。我通过创建一个类来做到这一点:

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 *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>

和component.ts:

import { alert } from './alert';

  alert: alert;

  ngOnInit() {

    this.alert = new alert();

  }

  editForm() {

    fetch(this.formService.formsUrl + "/" + this.formService.form.id, {

      method: 'PUT',

      body: JSON.stringify(this.formService.form),

      headers: {

        "Content-type": "application/json; charset=UTF-8"

      }

    })

    .then(response => response.json())

    .then(json => console.log(json));

    this.alert.setAlert("Post has been successfully saved !");

  }

有人告诉我,更好的方法是使用EventEmmiter。那么您能给我一些建议吗?

2 个答案:

答案 0 :(得分:0)

通常,您不是自己开发它,而是使用库来显示消息。常用的是来自Angular Material的snackbar

答案 1 :(得分:0)

在Julien的回答(这是一个非常好的内置建议)的基础上,我建议您创建一个service并实现所需的各种通知,然后致电服务为您显示通知如果发生任何更改,您只需修改服务即可。

import { Injectable } from '@angular/core';
import { MatSnackBar, MatSnackBarRef } from '@angular/material';

@Injectable({
  providedIn: 'root'
})
export class NotificationService {

  constructor(public snack: MatSnackBar) { }
  showNotification(message: string, action: any, duration: number): MatSnackBarRef<any> {
    return this.snack.open(message, action, { duration: duration , verticalPosition: 'top', horizontalPosition: 'right'});
  }
}
然后,您只需要在组件中注入服务并使用showNotification函数,您当然可以根据需要进行更改。