我正在尝试实现一个通用的 http 处理程序错误,但我发现了一个错误的行为。我的错误组件仅在第二次单击后才更新消息错误,但我不知道为什么。
代码在 StackBlitz 中可用:在此处输入链接描述
在 app.component.ts 点击我尝试一个 http 请求,它会失败,只是为了抛出一个错误。
onClick() {
this.http
.get('http://localhost:8080/test')
.pipe(catchError(this.errorHandler))
.subscribe(() => {});
}
errorHandler(error: HttpErrorResponse) {
return throwError(error.message);
}
所有错误都在 global.error.ts 中处理,每个错误都添加到 error.service.ts 中:
export class GlobalErrorHandler implements ErrorHandler {
constructor(private errorService: ErrorService) {}
handleError(error: Error) {
this.errorService.add('New Error');
}
}
error.service.ts 使用 BehaviorSubject 并通知我的 error.component.ts:
export class ErrorService {
public notification = new BehaviorSubject<string>('Initial Value');
add(err: string) {
this.notification.next(err);
}
}
最后,error.component.ts 必须在屏幕上更新消息错误,但它只在第二次单击时有效,但 console.log 完美运行。
export class ErrorComponent implements OnInit {
public errorMessage: string = '';
constructor(public errorService: ErrorService) {}
ngOnInit() {
this.errorService.notification.subscribe({
next: (notification) => {
console.log('Error Component');
this.errorMessage = notification;
},
});
}
}
问题:
- 这种行为有什么原因吗?
- 对实现全局处理程序 Http 错误有什么建议吗?