如果内部Observable在Observable of Observable流中失败,如何继续接收值?

时间:2018-12-01 21:53:58

标签: angular rxjs observable

我处于这种情况,我有一个类似这样的Observables:

 public outerFunction(
    collections: someObject
  ): Observable<someOtherObject> {

    const outerObservable$ = new Observable<Observable<someOtherObject>>(
      (observer) => {

        const collKeys = Object.keys(collections);
        for (const id of collKeys) {
          if (collections[id]) {
            const innerObs$ = this.functionThatReturnsObs(
              collections[id]
            )
            observer.next(innerObs$);
          }
        }
      }
    );
    return outerObservable$.pipe(mergeAll(1));
}

functionThatReturnsObs进行Http调用以检索一些数据,

我的问题是;如果其中一个呼叫失败,则不会从其他http呼叫中获取任何其他数据,就像流已中断一样。

我想做类似的事情:

this.outerFunction(collections).piep(
map((data) => /* do something with this data*/),
catchError((error) => /* in case of failure of one of the http calls do something */ ));

更新

致电observer.next(innerObs$.pipe(() => empty());似乎对我不起作用,

但是我通过从Observable<Observable<someOtherObject>>返回outerFunction,然后像这样使用mergeMap来实现期望的行为:

  public outerFunction(
    collections: someObject
  ):Observable<Observable<someOtherObject>> {

    const outerObservable$ = new Observable<Observable<someOtherObject>>(
      (observer) => {

        const collKeys = Object.keys(collections);
        for (const id of collKeys) {
          if (collections[id]) {
            const innerObs$ = this.functionThatReturnsObs(
              collections[id]
            )
            observer.next(innerObs$);
          }

        }
      }
    );
      return outerObservable$;
}

然后:

this.outerFunction(collections).pipe(
mergeMap((innerObs$) => innerObs$.pipe(
map((data) => /* do something with this data*/),
catchError((err) => /* in case of err handle the faild HTTP call */)
)),
);

但是我不知道为什么会这样,有人可以解释为什么吗?

1 个答案:

答案 0 :(得分:3)

您已经有了使用catchError的正确想法。为防止外部可观察物死亡,只需将其添加到内部可观察物即可。例如

observer.next(innerObs$.pipe(catchError(() => EMPTY)));