【问题标题】:Run an array of http calls sequentially in Angular在 Angular 中按顺序运行一组 http 调用
【发布时间】:2019-07-03 10:52:40
【问题描述】:

我已经多次看到这个问题,但我不知道如何实施它来解决我的问题。

我基本上有一组需要按顺序执行的 http 调用。具体来说,我需要执行一个,等待它返回然后执行下一个。

let requests = [
  this.http.post('http://localhost:4200/api/value', 'one'),
  this.http.post('http://localhost:4200/api/value', 'two'),
  this.http.post('http://localhost:4200/api/value', 'three'),
  this.http.post('http://localhost:4200/api/value', 'four'),
];

所以我目前正在使用 forkJoin 但这不是我想要的同时运行请求。

forkJoin(observableBatch).subscribe(result => {
  // success
}, error => {
  // log error
}); 

我使用concatMap 阅读可能是答案,但我如何在可观察的数组上使用它?

【问题讨论】:

标签: angular rxjs


【解决方案1】:

试试RXJS的concat函数,试试这个

import { concat } from 'rxjs';

let requests = [
  this.http.post('http://localhost:4200/api/value', 'one'),
  this.http.post('http://localhost:4200/api/value', 'two'),
  this.http.post('http://localhost:4200/api/value', 'three'),
  this.http.post('http://localhost:4200/api/value', 'four'),
];

concat(...requests).subscribe(result => {
  // success
}, error => {
  // log error
}); 

【讨论】:

  • 从 'rxjs' 导入 { concat }。它不是运营商。而且您错过了订阅电话。
  • 这四个调用中的每一个都会触发订阅结果,还是仅在所有四个调用都执行后触发?我有一个场景,我需要在后续请求的标头中发送响应 eTag
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 1970-01-01
  • 2017-09-29
  • 1970-01-01
相关资源
最近更新 更多