4中的多个顺序API调用

4中的多个顺序API调用

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

问题描述

我有一组图像对象。

console.info('gallery', galleryArray);

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

The length of this array can be different. I have to make a POST request on every item of this array. The next request must be executed only after previous request has finished.

所以我试图创建一个Observable请求数组,如下所示:

So I tried to make an array of Observable requests like this:

  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的新手。

The question is how to perform those requests, so that every api call goes only after previous has finished? Help please. I'm new to 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 块中获得单个调用的结果。

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.

在您的特定情况下:

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

这篇关于Angular 4中的多个顺序API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 15:13