【发布时间】: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