簡體   English   中英

Angular Http forEach 中的請求,等待完成請求直到繼續循環

[英]Angular Http Request in forEach, wait to finish request until continue looping

我正在遍歷選定的文件,以便首先獲得簽名的 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)
       });
});

我假設getSignedURL()的 observable 使用toPromise()轉換為 promise 。 如果是這樣,請將其刪除並將其作為可觀察對象返回。

然后,您可以使用Array#map將數組中的元素 map 到可觀察對象,使用 RxJS from function 以及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 => { }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM