【问题标题】:Angular, how to make consecutive, dependent http get requestsAngular,如何进行连续的、依赖的http get请求
【发布时间】:2020-06-18 19:51:53
【问题描述】:

我想在另一个完成后执行一个 http get 请求。第二个请求的端点 URL 需要依赖于第一个请求。

我尝试在 Angular 中使用类似的东西嵌套请求:

this.http.get(endpoint1).subscribe(
   success => {
      this.http.get(endpoint2 + success).subscribe(
         anotherSuccess => console.log('hello stackoverflow!')
      );
   }
);

关于stackoverflow的第一个问题,如果我应该提供更多细节,请告诉我。

【问题讨论】:

标签: javascript angular http get observable


【解决方案1】:

here you can find how to do that,你有多种选择:

订阅:

this.http.get('/api/people/1').subscribe(character => {
  this.http.get(character.homeworld).subscribe(homeworld => {
    character.homeworld = homeworld;
    this.loadedCharacter = character;
  });
});

使用mergeMap

this.homeworld = this.http
  .get('/api/people/1')
  .pipe(mergeMap(character => this.http.get(character.homeworld)));

有一个带有 forkJoin 的版本,但与 subscribe 和 mergeMap 相比并不明确。

【讨论】:

    【解决方案2】:

    您可能应该尝试使用 ngrx (redux) 根据 success 操作触发第二个请求。

    流程应该是这样的:从组件分派一个动作 -> 调用第一个请求 -> 请求触发一个成功动作 -> 成功效果触发带有来自前一个请求的有效负载的第二个请求。

    Read the docs here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      相关资源
      最近更新 更多