1

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?

2
  • What should happen if the first one fails - would you like to continue with the second in that case? Commented Feb 27, 2021 at 10:36
  • @NicholasK no, if the first one fails, the second one shouldn't be called (the behaviour now is correct). I want to just handle the error of the first one. Commented Feb 27, 2021 at 10:41

1 Answer 1

1

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';
Sign up to request clarification or add additional context in comments.

2 Comments

thank you. Only for the sake of curiosit: Would be there also a way in order to continue with the second call, in case that the first one would fail?
You can try using onErrorResumeNext for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.