繁体   English   中英

Angular 4中的多个顺序API调用

[英]Multiple Sequential API calls in Angular 4

我有一组图像对象。

console.info('gallery', galleryArray);

在此输入图像描述

这个数组的长度可以不同。 我必须对此数组的每个项目发出POST请求。 只有在上一个请求完成后才能执行下一个请求。

所以我试着像这样制作一个Observable请求数组:

  let requests: Observable<Response>[] = [];
  galleryArray.forEach((image) => {
    requests.push(this._myService.uploadFilesImages(image));
  });

  console.info(requests);

在此输入图像描述

我的服务如下:

uploadFilesImages(fileToUpload: any): Observable<any> {
  const input = new FormData();
  input.append('image', fileToUpload);
  return this.uploadHttp.post(`${this.endpoint}`, input)
  .map(
    (res: Response) => res.json()
  );
}

问题是如何执行这些请求,以便每个api调用仅在之前完成之后才会执行? 请帮忙。 我是Angular的新手。

您正在寻找concatMap运算符:

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

concatMap运算符仅在observable上的当前迭代完成后才会发出。 您将在subscribe块中获得各个调用的结果。

在您的特定情况下:

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

您可以使用async / await为Promise解决此问题:

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

确保将async放在执行此代码的方法后面。 链接到我的答案了类似的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM