【问题标题】:Angular 2 Observable http service error handlingAngular 2 Observable http 服务错误处理
【发布时间】:2016-05-23 17:07:02
【问题描述】:

我了解 Observable 数据服务的核心概念,但是当我需要更强大的服务时遇到了麻烦。

对于用户查询,我必须进行一系列 http 调用,以便首先查询用户对象,然后在获取用户对象后查询其他数据。因为这些额外的调用依赖于抓取的用户对象。订阅者接收整个用户对象以及它能够获取的任何额外数据。

我目前正在使用userSource.mergeMap(user => extraDataNeeded(user)) 来返回组合的 Observable。 其中extraDataNeeded 返回Observable.forkJoin(...OBSERVABLES) OBSERVABLES 是一个向用户对象添加额外数据的 http 调用数组。

我的问题是,当这些额外的 http 调用之一失败时,链中的其余部分将被取消。我想要从userSource.mergeMap(user => extraDataNeeded(user)) 创建的最高阶可观察对象,以使所有http 调用都不管是否失败。我希望userSource.mergeMap(user => extraDataNeeded(user)) 的订阅者能够接收用户对象以及它能够获取的任何数据,以及任何内部 http 调用失败的任何错误。如果原始 userSource 失败,则完全失败,没有成功响应。

【问题讨论】:

    标签: angular rxjs observable


    【解决方案1】:

    您可以将catch 块添加到您的每个OBSERVABLES 中,这样失败响应只会在next 块中返回错误正文。

    source1.catch(e => Rx.Observable.of({error: e}));
    source2.catch(e => Rx.Observable.of({error: e}));
    
    //or made modular
    
    function handler(e) { return Rx.Observable.of({error: e}));
    
    var safeSource1 = source1.let(handler);
    var safeSource2 = source2.let(handler);
    

    然后在构建对象时,您只需要适当地处理这些错误:

    Rx.Observable.forkJoin(safeSource1, safeSource2, sources => {
      //Totally made up
      var combined = {components: [], errors: []};
      for (let resp of sources) {
        if (resp.error)
          combined.errors.push(resp.error);
        else
          combined.components.push(resp);
      }
    });
    

    来自userSourceObservable 的错误仍将传递给错误处理程序并完全绕过forkJoin

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-16
      • 2016-10-25
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 2016-07-12
      相关资源
      最近更新 更多