Using FileTransfer plugin pass data to next request in for loop

Issue

I have a image upload Request with a param. I want to send response from 1st request to all next requests inside for loop.

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});
      }
    })
  }

Camera Service .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) => {
      })
    })
  }

Solution

Solved it by Converting my UploadFileMedia() from Promise to Observable in my camera.service.ts

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);
      });
    });
  }

and inside my 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();
            }
          })
        })
      }
    })
  }

Idea taken From:

Another Answer for Same Problem

Answered By – Najam Us Saqib

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published