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

问题描述 投票:0回答:2

我正在创建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 !");

  }

我被告知更好的方法是使用EventEmitter。那么请你就如何做到这一点给我一些建议?

angular typescript
2个回答
0
投票

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


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'});
  }
}
Then you just need to inject the service in your components and use the showNotification function which of course you can change based on your needs.
© www.soinside.com 2019 - 2024. All rights reserved.