使用 FileTransfer 插件将数据传递给 for 循环中的下一个请求

Using FileTransfer plugin pass data to next request in for loop

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

Page.page.ts

//function to take Photos    
 takePhoto() {
   this.camera.takePhoto().then((res: any) => {
     res.map((v) => {
       this.uploadMedia(v.fullPath, v.fullPath.split('/').pop())
     })
   })
 }


// function to upload Photos    
 uploadMedia(path, type) {
    this.imgLoader = true;
    this.camera.uploadFileMedia(path, 'UploadImage', type, this.postId).then((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});
      }
    })
  }

相机服务.ts

uploadFileMedia(path: string, url: string, fileType: string, post_id): Promise<any> {
    const fileTransfer: FileTransferObject = this.transfer.create();
    let options: FileUploadOptions = {
      fileKey: 'images',
      fileName: fileType,
      params: {post_id: post_id }
    }
    return new Promise(resolve => {
      fileTransfer.upload(path, url, options).then((data) => {
        resolve(res)
      }, (err) => {
      })
    })
  }

通过将 UploadFileMedia()Promise 转换为 camera.service.ts

中的 Observable 解决了这个问题
UploadFileMedia(path: string, url: string, fileType: string, post_id): Observable<any> {
    const fileTransfer: FileTransferObject = this.transfer.create();
    let options: FileUploadOptions = {
      fileKey: "images",
      fileName: fileType,
      chunkedMode: false,
      params: { post_id: post_id }
    };
    return new Observable(result => {
      fileTransfer.upload(path, url, options).then((data) => {
        let res = JSON.parse(data.response);            
        result.next(res);    
      }, err => {
        result.error(err);
      });
    });
  }

在我的 page.ts 里面:

takePhoto = async () => {
    this.camera.takePhoto().then(async (res: any) => {
      for (let v = 0; v < res.length; v++) {
        await new Promise((resolve, reject) => {
          this.camera.UploadFileMedia(res[v].fullPath, 'UploadImage', res[v].fullPath.split('/').pop(), this.postId).subscribe((res: any) => {
            console.log(res);
            if (res.status == true) {
              this.postId = res.data.post_id;
              this.userImages.push({ img: res.data});
              resolve(true)
            } else {                  
              reject();
            }
          })
        })
      }
    })
  }

想法取自: