如何捕获在 Angular 模板中订阅的可观察对象的异常?

How to catch exceptions for observables subscribed in Angular template?

在 Angular (4.3.6) 应用程序中,我使用异步管道在模板中使用可观察对象。

在某些情况下,当我从 HTTP GET 获得 404 时,Angular 会冒出异常并且应用程序变得无响应。 我已经看到我可以在我的服务中使用 .catch() 方法,但是我的组件中没有直接的 .subscribe() 方法,我该如何处理异常?

文档服务[=​​30=]:

public getDocument() {
   return this.getDocument(serverUrl).catch((err) => this.handleError(err));
}

private handleError(error: Response) {
    return Observable.throw(error);
}

分量:

public ngOnInit() {

   const document$ = this.reference$
        .filter((i) => !!i)
        .combineLatest(this.documentService.getBranch(),
        (r: any, branch: string) => {
            return this.documentService.getDocument(r.Id, r.targetId, this.GetHeadBranch(branch));
        }).switch();
   }

模板:

<div *ngIf="document$|async; let document;">
  ....
</div>

是否有像我的案例那样使用可观察对象捕获异常的最佳实践?

据我所知from the async source code,没有办法指示管道在发生错误时做什么。管道只是抛出错误。所以看起来你有两个选择:

您可以创建自己的带有附加参数的管道。可能是发生错误时要执行的回调函数。可以将回调与抛出的错误一起传递给可观察源,这样您就可以显示适当的错误消息,甚至可以根据需要重新订阅。

您可以使用 catch 并以某种方式处理服务中的错误,将返回的内容格式化以适合视图。

private handleError(error: Response) {
    // return Observable.throw(error); //will crash the app when fed to async pipe
    return Observable.of(this.errorDocument); //something the async pipe can display
}

See my example