在Angular 6中顺序执行http请求

时间:2018-12-06 15:00:14

标签: angular typescript angular6 observable

我需要按顺序向服务器发送多个HTTP PUT请求(仅在完成上一个请求后才启动下一个请求,但请求的数目是固定的)。 如果我使用下面的源代码,则将发送所有请求

 `listURL.forEach(url => {
    const req = new HttpRequest('PUT', url, formData, { reportProgress: true});
    httpClient.request(req).subscribe(event=>{});
  });`

反正有顺序执行请求吗?

3 个答案:

答案 0 :(得分:4)

您可以将async / await与Promise配合使用来简化此行。使用toPromise()

将可观察值转换为承诺
async doSomethingAsync() {
    for(let url of listURL) {
        const req = new HttpRequest('PUT', url, formData, { reportProgress: true});
        const result = await httpClient.request<ModelHere>(req).toPromise();
        // do something with result
    }
}

有关异步/等待的更多信息,请参见此出色的答案,然后滚动至标题ES2017+: Promises with async/await

答案 1 :(得分:3)

使用reduceswitchMap

['url 1', 'url 2'].reduce((acc, curr) => acc.pipe(
  mergeMap(_ => this.mockHttpCall(curr)),
  tap(value => console.log(value)),
), of(undefined)).subscribe(_ => console.log('done !'));

Stackblitz

答案 2 :(得分:1)

如果您不熟悉rxjs,也许可以尝试以下方法?

let requests = listURL.map(url => new HttpRequest('PUT', url, formData, { reportProgress: true});

function do_seq(i) {
  httpClient.request(requests[i]).subscribe(event => {
   if (i < requests.length - 1) do_seq(i + 1);
  });
 }

do_seq(0);