[Fixed] 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:

    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:

    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.

Leave a Reply

(*) Required, Your email will not be published