progressEvent.lengthComputable gives false value

I cannot seem to get progress value

.ts

  download(attachment){
    const fileTransfer: TransferObject = this.transfer.create();

    this.platform.ready().then(() => {
      if (this.platform.is('ios')) {
        this.storageDirectory = this.file.documentsDirectory;
      }
      else if (this.platform.is('android')) {
         this.storageDirectory = this.file.externalRootDirectory+ '/Download/';
  } else {
      return false;
  }

  this.is_downloading = true;   // show progressBar

  fileTransfer.onProgress((progressEvent: ProgressEvent) => {
    this.ng_zone.run(() => {
      console.log('progressEvent.lengthComputable: ', progressEvent.lengthComputable)  
      // SHOWS FALSE
       if (progressEvent.lengthComputable){
        console.log('progressEvent.loaded: ', progressEvent.loaded)
       // if condition removed, .loaded seems fine showing value
        console.log('progressEvent.total: ', progressEvent.total)
       // no total , showing '0'
        let progress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
          if (progress > 100) progress = 100;
          if (progress < 0) progress = 0;
          this.progress = progress;
        console.log('progress : ', progress);
        // 'Infinity'
       }
    });
  });

  const url = 'some url';
  let trustAllHosts = true;
  fileTransfer.download(url, this.storageDirectory + attachment.fileName, trustAllHosts).then((entry)=> {
    
    const alertSuccess = this.alertCtrl.create({
      title: 'Download Succeeded',
      subTitle : attachment.fileName + ' was successfully downloaded to '+ entry.toURL(),
      buttons: ['Ok'] 
    });

    alertSuccess.present();
  }, (err) => {
    const alertFailure = this.alertCtrl.create({
      title: 'Download Failed',
      subTitle: attachment.fileName + ' was not successfully downloaded. Error code: '+ err,
      buttons: ['Ok']
    });
    alertFailure.present();
  });
});

.html

 <div *ngIf="is_downloading">
  <span>File</span>
  <progress-bar [progress]="progress"></progress-bar>
 </div>

I don’t use callbacks in Ionic. They work, but they are such a pain. If I were coding your project, I’d turn the onProgress callback into an Observable with Observable.create() and send that Observable as an input to a progress bar component. It might take some getting used to, but it makes for much cleaner code.

1 Like

can you show a simple example of how to do this , thanx

Multiple code examples in the rxjs 5 Observable.create() doc.

I went through some examples , but I can’t seem to grasp the full concept, and I am facing problems in understanding how to convert onProgress to observable, there is ngzone and also another callback inside it Math.round … if its not much to ask , can you convert this function or at least a simple example to show case what you meant.

I am not sure why lengthComputable return a false value.