简体   繁体   中英

RxJs consequent observables: continue execution if an error occurs

I need to combine two api calls - serviceA and serviceB . serviceB should be called right after serviceA . However, if serviceA fails, the code should continue execution and call serviceB .

What's the right way to do it, using RxJS?

Here's what I've tried:

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))
      );
    })
  );

You need to put the catchError earlier in the pipe if you want to catch errors from service 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))
);

In the above code, the first catchError will catch errors that occurred in the call to serviceA.getData() and return an observable the switchMap will receive as dataA . Execution will continue, so serviceB gets called regardless of whether or not an error has occurred.

The second catchError will catch errors from serviceB.getData() .

This interactive StackBlitz demonstrates this behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM