【问题标题】:How to catch exceptions for observables subscribed in Angular template?如何捕获 Angular 模板中订阅的可观察对象的异常?
【发布时间】:2018-05-01 10:36:57
【问题描述】:

在一个 Angular (4.3.6) 应用程序中,我使用异步管道在模板中订阅 observables。

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

文档服务

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>

在我的案例中,是否有使用可观察对象捕获异常的最佳实践?

【问题讨论】:

    标签: angular exception-handling angular2-observables


    【解决方案1】:

    据我所知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

    【讨论】:

    • 遗憾的是还没有更好的方法来处理异常。自定义管道将需要一些额外的步骤(订阅 observable、处理值、在异常情况下重定向),但如果可以将其设为通用,那么从长远来看它将是一个胜利。
    猜你喜欢
    • 1970-01-01
    • 2019-02-25
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2020-06-28
    • 2022-01-01
    相关资源
    最近更新 更多