0

Hi I need to nest 3 calls in Angular9. where :

  1. All call's are inter-dependent
  2. All calls can give error

a.How can i write the code in a better way?

b.Can i use RXJS?

c.How to nest along with error block in RXJS?

example:

this.http.get('/api/people/1').subscribe(character => {
      this.http.get('/api/people/character ').subscribe(homeworld => {
            this.http.get('/api/people/character/homeworld  ').subscribe(finalResponse=> {
                 console.log(finalResponse);
            },
             error =>{
                  console.log(error);
            });
      },
      error =>{
           console.log(error);
      });
},
error =>{
   console.log(error);
});
1
  • This article may help you understand the main mechanics of rxjs with http calls Commented Apr 29, 2020 at 6:35

1 Answer 1

2

You will need a higher-order mapping operator to be able to make only once subscription, for example, a switchMap.

const getPeople = id => this.http.get(`/api/people/${id}`);
const getCharacter = character => this.http.get(`/api/people/${character}`);
const getCharacterAgain = character => this.http.get(`/api/people/character/${character}`);

getPeople(1).pipe(
  switchMap(getCharacter),
  switchMap(getCharacterAgain),
).subscribe(...);
Sign up to request clarification or add additional context in comments.

Comments

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.