首页 > 解决方案 > Angular 6中使用行为主题的通知服务弹出窗口

问题描述

我正在尝试使用来自角度 6 的通知服务的文本消息来查看组件中错误的弹出窗口。当我发现错误时,我会调用我的通知服务。

首先是通知服务:

private _notification: BehaviorSubject<string> = new BehaviorSubject(null);
private notification$: Observable<string> = this._notification.asObservable().pipe(
  publish(),
  refCount()
);

constructor() { }

notify(message: string) {
  this._notification.next(message);
  setTimeout(() => this._notification.next(null), 3000);
}

错误处理服务:

export class GlobalErrorHandlerService implements ErrorHandler {

  constructor(private injector: Injector) { }

  handleError(error: any) {
    const router = this.injector.get(Router);
    console.log('URL: ' + router.url);

    const loggerService = this.injector.get(LoggerService);
    loggerService.log(error);

    const notificationService = this.injector.get(NotificationService);

    if (error instanceof HttpErrorResponse) {
      // BackEnd returns unsuccessful response codes(404,...)
      console.error('Status Code: ', error.status);
      console.error('Response body:', error.message);
      console.error('Error Message: ', error.error);

      notificationService.notify(`${error.status} - ${error.error}`);
    } else {
      // client side or network error occurred.
      console.error('Error occurred: ', error.message);
      notificationService.notify(`${error.status} - ${error.message}`);
    }
  }
}

所以我的问题是如何在向我的通知服务触发新错误消息时显示弹出窗口。我知道如何从通知服务订阅 observable,但我不知道如何在组件中将其与查看弹出窗口结合起来。

一个简单的代码示例或有用的链接会很好:)

提前谢谢了

编辑:为了澄清我的问题,这里有一个示例使用场景:

ComponentA 向后端发送一个 POST 请求。如果失败,错误处理服务会捕获错误并将错误消息发送到我的通知服务。现在应该有一个弹出消息显示来自notification$的错误消息。
所以我知道如何订阅通知$,但我不知道如何显示来自通知$ 的消息的弹出窗口。我应该为此使用服务还是使用其他组件或其他东西..?

标签: angulartypescriptrxjsobservable

解决方案


简单的方法是您可以在应用程序的根目录中放置一个通知组件,并在应用程序模块中提供通知服务。通知服务可以远程控制通知和消息的可见性。

<html>
<app>
<notification message="notificationService.message" *ngIf="notficationService.active"> </notification>
</app>
<html>

或者,您可以选择采用动态组件方法 https://itnext.io/angular-create-your-own-modal-boxes-20bb663084a1


推荐阅读