【问题标题】:PopUp window for notification service using behaviour subject in Angular 6Angular 6中使用行为主题的通知服务弹出窗口
【发布时间】:2018-10-24 00:13:10
【问题描述】:

我正在尝试使用来自角度 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$ 的错误消息。
所以我知道如何订阅通知$,但我不知道如何显示来自通知$ 的消息的弹出窗口。 我应该为此使用服务还是使用其他组件或其他东西..?

【问题讨论】:

  • 您只需创建一个订阅notification$ 的组件,例如使用async 管道:service.notification$ | async
  • @martin 感谢您的回答。我为我的问题添加了详细的使用场景。正如上面已经提到的,我知道如何订阅通知$。

标签: angular typescript rxjs observable


【解决方案1】:

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

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

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

【讨论】:

  • 我将您的方法与链接中的自定义模式框结合使用 - 感谢您的提示:)
猜你喜欢
  • 1970-01-01
  • 2023-01-25
  • 2019-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多