Как вложить http звонки в angular - PullRequest
0 голосов
/ 28 апреля 2020

Привет, мне нужно вложить 3 звонка в Angular9. где:

  1. Все вызовы взаимозависимы
  2. Все вызовы могут выдавать ошибку

a. Как лучше написать код?

b.Можно ли использовать RX JS?

c. Как вкладывать данные вместе с блоком ошибок в RX JS?

пример:

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 Ответ

2 голосов
/ 28 апреля 2020

Вам понадобится higher-order mapping operator, чтобы иметь возможность сделать только одну подписку, например, 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(...);
...