binoculars
binoculars

Reputation: 2274

Function inside function: Angular 2

I'm using this function (part of a cordova plugin) in Angular2:

download()
{
//some download stuff

// ==> here this.percentage=50 works

//show progress of download
 this.fileTransfer.onprogress = function(progressEvent) {
  if (progressEvent.lengthComputable) {
      console.log((progressEvent.loaded / progressEvent.total)); // works great
      this.setpercentage((progressEvent.loaded/progressEvent.total)*100) // doesn't work
      } else {}
  }
}

setpercentage(perc)
{
  this.percentage = perc;
}

But percentage isn't updating. It says setpercentage() is not a function.

I'm new to Angular, and I've read somewhere about arrow functions. So I gave it a try and changed it to:

this.fileTransfer.onprogress((progressEvent)=>{
    if (progressEvent.lengthComputable) {
        console.log((progressEvent.loaded / progressEvent.total));
        this.setpercentage((progressEvent.loaded/progressEvent.total)*100)
    } else {}
});

But that breaks the whole script. The console log isn't showing the percentage anymore.

What am I doing wrong?

Update: I tried @echonax suggestion, without luck:

download()
{
        this.setpercentage(50); <-- works

        this.fileTransfer.download(**download stuff**);

        var self = this; // store outer this in a variable
        this.fileTransfer.onprogress = function(progressEvent) {
            if (progressEvent.lengthComputable) {
                console.log((progressEvent.loaded / progressEvent.total)); // works great
                self.setpercentage(60); // <-- doesn't work
            } else {}
        }
}

setpercentage(perc)
{
    this.percentage = perc;
}

Upvotes: 2

Views: 6089

Answers (2)

binoculars
binoculars

Reputation: 2274

As pointed out by rapropos, injecting a ChangeDetectorRef and calling its detectChanges() method after modifing the percentage property of the controller, resolves this issue!

Upvotes: 0

eko
eko

Reputation: 40647

Change

this.fileTransfer.onprogress = function(progressEvent) {

to

this.fileTransfer.onprogress = (progressEvent)=> {

Your this is not refering to your component

this is similar to doing

var self = this; // store outer this in a variable
this.fileTransfer.onprogress = function(progressEvent) {
  if (progressEvent.lengthComputable) {
      console.log((progressEvent.loaded / progressEvent.total)); // works great
      self.setpercentage(60, self) // <-- use it here
      } else {}
}

setpercentage(perc, self)
{
    setTimeout(()=>{
      self.percentage = perc;
    },0);
}

But with the second approach your this inside the setpercentage method will refer to the functions instance and not to the component

Upvotes: 5

Related Questions