Abhijit Roy
Abhijit Roy

Reputation: 1

How to nest http calls in angular

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

Upvotes: 0

Views: 144

Answers (1)

Yasser Nascimento
Yasser Nascimento

Reputation: 1381

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(...);

Upvotes: 2

Related Questions