Execute http request sequentially in Angular 6

假装没事ソ 提交于 2019-12-13 16:25:06

问题


I need to send multiple HTTP PUT request to server sequentially (after the next request is only started after completing the previous request, the number of request is not fixed). If I use the below source code, all request will be sent

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

Is there anyway to execute the requests sequentially?


回答1:


If you are not familiar with rxjs, perhaps you can try the following?

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



回答2:


You could use async/await with Promise to stream line this. Convert the observable to a promise using 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
    }
}

For more on async/await see also this excellent answer and scroll to the heading ES2017+: Promises with async/await.




回答3:


use reduce and switchMap :

['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



来源:https://stackoverflow.com/questions/53654176/execute-http-request-sequentially-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!