本文介绍了Angular 2:将多个http调用合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于上传图片的服务.要上传图片,我要做的就是

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 ?

编辑这是我的服务

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

推荐答案

如果要并行运行所有请求,可以使用forkJoin():

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

您最终可以使用Observable.merge()接收结果到达时的结果,或者最终Observable.concat()接连调用请求.

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

这篇关于Angular 2:将多个http调用合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 15:13