【问题标题】:How to nest http calls in angular如何以角度嵌套http调用
【发布时间】:2020-04-28 17:01:15
【问题描述】:

您好,我需要在 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);
});

【问题讨论】:

  • This article 可以帮助你理解 rxjs 与 http 调用的主要机制

标签: http rxjs nested angular-httpclient


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2019-11-19
    • 2019-08-16
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多