首页 > 解决方案 > forEach中的Angular Http请求,等待完成请求直到继续循环

问题描述

我正在遍历选定的文件,以便首先获取签名的 url,然后将其直接放入 S3 存储桶。我现在的问题是,我想等到 forEach 中的所有内容都完成,然后继续循环。

我现在遇到的是代码同时直接查询每个文件的签名 url。

谢谢你的帮助

result['files'].forEach(file => {
    this.fileService.getSignedURL(this.vehicleId, file.name, file.type, file.size)
       .then(res => {
          this.pushFile(file, app, description, languageKey, file.name, res.path, res.signed_url)
       });
});

标签: angulartypescript

解决方案


我假设 observable fromgetSignedURL()使用toPromise(). 如果是这样,请将其删除并将其作为可观察对象返回。

然后,您可以使用 将数组中的元素映射到可观察Array#map对象,使用 RxJSfrom函数和concatMap运算符来依次触发对元素的请求。

尝试以下

from(
  result['files'].map((file) =>
    this.fileService.getSignedURL(this.vehicleId, file.name, file.type, file.size).pipe(
      concatMap((res) => 
        this.pushFile(file, app, description, languageKey, file.name, res.path, res.signed_url)
      )
    )
  )
).subscribe({
  next: res => { },
  error: error => { }
});

推荐阅读