首页 > 解决方案 > RxJs consequent observables:如果发生错误则继续执行

问题描述

我需要结合两个 api 调用 -serviceAserviceB. serviceB应该在之后调用serviceA。但是,如果serviceA失败,代码应该继续执行并调用serviceB.

使用 RxJS 的正确方法是什么?

这是我尝试过的:

this.serviceA.getData(id).pipe(
    map((data) => {
      return { ...data, test: "abc" };
    }),
    mergeMap((res) => {
      return this.serviceB.getData(id).pipe(
        map((scores) => this.handleData(scores)),
        catchError(() => of(res))
      );
    })
  );

标签: javascriptangularrxjs

解决方案


catchError如果要从服务 A 中捕获错误,则需要将前面的内容放入管道中:

this.serviceA.getData().pipe(
    catchError(errA => of(errA)),
    map(dataA => ({ ...dataA, test: "abc" })),
    switchMap(objA => this.serviceB.getData(objA)),
    catchError(errB => of(errB)),
    map(dataB => this.handleData(dataB))
);

在上面的代码中,第一个catchError将捕获调用中发生的错误serviceA.getData()并返回一个 observableswitchMap将接收为dataA. 执行将继续,因此无论是否发生错误,都会调用 serviceB。

第二个catchError将捕获来自serviceB.getData().

这个交互式StackBlitz演示了这种行为。


推荐阅读