Angular 4 中的多个顺序 API 调用 [英] Multiple Sequential API calls in Angular 4

查看:23
本文介绍了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 运算符:

You are looking for the concatMap operator:

示例

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 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆