【问题标题】:Pass data to next request in for loop将数据传递给 for 循环中的下一个请求
【发布时间】:2021-10-08 12:43:17
【问题描述】:

我有一个带有param 的图片上传请求。我想将第一个请求的响应发送到 for 循环内的所有下一个请求。

for (let i = 0; i < e.target.files.length; i++) {
  this.http.uploadImages(e.target.files[i], 'UploadImage', this.postId).subscribe((res:any)=>{
    if(res.status == true){
      this.postId = res.data.post_id; // i want to pass this postId to All other Requests. 
      this.userImages.push({ img: res.data });
    }
  })
}

【问题讨论】:

  • 您不应该在第一个请求的订阅中发出任何其他请求。得到承诺并等待它

标签: javascript angular ajax for-loop file-upload


【解决方案1】:

下面的 sn-p 将依次执行每次上传,每次更新 this.postId 值。使用箭头函数this 上下文被保留。

(如果您的 this.http.uploadImages 方法已经返回了一个 Promise,则您不需要实例化一个新的 Promise)

const upload = async () => {
    for (let i = 0; i < e.target.files.length; i++) {
        await new Promise((resolve, reject) => {
            this.http
                .uploadImages(e.target.files[i], 'UploadImage', this.postId)
                .subscribe((res: any) => {
                    if (res.status) {
                        this.postId = res.data.post_id;
                        this.userImages.push({img: res.data});

                        resolve();
                    } else {
                        reject();
                    }
                });
        });
    }
};

【讨论】:

【解决方案2】:

在 for 循环之前创建新变量并存储响应中的 postId。比在请求中检查这个变量。如果为空 - 跳过,如果不是 - 发送

【讨论】:

    猜你喜欢
    • 2021-10-08
    • 1970-01-01
    • 2011-09-27
    • 2022-01-21
    • 2020-12-13
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多