简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM