Search code examples
javascriptangularrxjsrxjs6

Rxjs make sequential calls using concatMap


I would like to make two sequentially calls (if the first one is completed, call the second one):

My Code is like:

        myApiClient
        .firstApiCall()
        .pipe(take(1),
            concatMap (firstResult => {
            doSomethingWithResponse(firstResult);
            return myApiClient.secondApiCall();
        }), take(1))
        .subscribe(secondResult => {
            doSomethingWithResponse(firstResult);
        }, error => {
            catchSecondApiCallError(error);
        });

First question: is that the right way to make sequential calls? Second question: How could I catch the error for the first Call?


Solution

  • Yes, that is the right way to chain sequential api calls using rxjs. For the second question you may make use of the catchError operator.

        myApiClient
        .firstApiCall()
        .pipe(
            take(1),
            catchError(e => {
              console.log('Error caught from first api ', e);
              return EMPTY;
            }),
            concatMap (firstResult => {
              doSomethingWithResponse(firstResult);
              return myApiClient.secondApiCall();
        }), take(1))
        .subscribe(secondResult => {
            doSomethingWithResponse(secondResult);
        }, error => {
            catchSecondApiCallError(error);
        });
    

    EMPTY is imported from:

    import { EMPTY } from 'rxjs';