Angular 4 中的多个顺序 API 调用

编程入门 行业动态 更新时间:2024-10-28 01:21:07
本文介绍了Angular 4 中的多个顺序 API 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一组图像对象.

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/';
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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 10:52:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/936291.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   顺序   Angular   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!