lecham
lecham

Reputation: 2464

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

Upvotes: 2

Views: 302

Answers (1)

BizzyBob
BizzyBob

Reputation: 14740

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.

Upvotes: 1

Related Questions