繁体   English   中英

如何在 angular 中嵌套 http 调用

[英]How to nest http calls in angular

嗨,我需要在 Angular9 中嵌套 3 个调用。 在哪里:

  1. 所有调用都是相互依赖的
  2. 所有调用都会出错

a.我怎样才能以更好的方式编写代码?

b.我可以使用 RXJS 吗?

c.如何与 RXJS 中的错误块一起嵌套?

例子:

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

您将需要一个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(...);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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