Multiple Sequential API calls in Angular 4

亡梦爱人 提交于 2019-12-05 08:38:44

You are looking for the concatMap operator:

Example

const apiRoot = 'https://jsonplaceholder.typicode.com/';
const urls = [];
for (let i = 0; i < 500; i++) {
  urls.push(apiRoot + 'posts/' + (i + 1));
}
Observable.of(...urls)
  .concatMap((url: string) => this.http.get(url))
  .subscribe((result) => console.log(result));

The concatMap operator only emits after the current iterated on observable is complete. You get the results of the individual calls in the the subscribe block.

In your particular case:

 Observable.of(...galleryArray)
  .concatMap((image) => this._myService.uploadFilesImages(image))
  .subscribe((result) => console.log(result));

You can use async / await for that purpose with the Promise resolve:

let requests: Observable<Response>[] = [];
galleryArray.forEach((image) => {
    await new Promise(resolve => {
        this._myService.uploadFilesImages(image)
            .subscribe(result => { 
                requests.push(result);         
                // resolve the promise once we have a result
                resolve();
            });
    });    
});

// This will only be called once all the api calls have been made
console.info(requests);

Make sure you put async behind the method where you are executing this code. Link to my answer for a similar question.

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