Angular 2 : merge several http calls into one

人盡茶涼 提交于 2019-12-11 04:44:17

问题


I have a service that is used to upload pictures. To upload a picture, all I do is

return this.http.post(/* ... */)

And I get a subscription I can subscribe to in my component. But when I want to upload several pictures, I have to do

for (let p of pics) { this.http.post(/* ... */); }

My problem is that I would like to return the results of all calls instead of just one call. Is that possible ?

EDIT Here is my service

addPictures(files: File[], folder: string): Observable<Parse.Object[]> {
  let hasError = false;
  for (let file of files) {
    let [type, ext] = file.type.split('/');
    if (type.toLowerCase() !== 'image' || !environment.imgExts.includes(ext.toLowerCase())) { hasError = true; }
  }
  if (hasError) { return Observable.throw('Invalid extension detected'); }

  let observables: Observable<Parse.Object>[] = [];

  for (let file of files) {
    // Get its size
    let img = new Image();
    img.onload = () => {
      // Create the Parse document
      let parseImg = { url: '', type: file.type, width: img.width, height: img.height };
      // Upload it on Amazon and add it to DB
      observables.push(this.addPicture(parseImg, file, folder));
    }
    img.src = window.URL.createObjectURL(file);
  }
  return Observable.forkJoin(observables);
}

回答1:


If you want to run all the requests in parallel you can use forkJoin():

const observables = pics.map(p => this.http.post(/* ... */));

Observable.forkJoin(observables)
  .subscribe(results => ...);

You could eventually use Observable.merge() to receive results as they arrive or eventually Observable.concat() to call requests one after another.



来源:https://stackoverflow.com/questions/45301745/angular-2-merge-several-http-calls-into-one

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