3

I use Ionic2 to build an app,which based on Angular2 and Cordova. when I use function setInterval to get a parameter called clickCount,it occurt an undefine error.

export class ItemDetailsPage {
static get parameters() {
    return [[NavController], [NavParams]];
}
constructor(nav, navParams) {
    this.nav = nav;
    this.clickCount = 0;
    this.selectedItem = navParams.get('item');
}

startTapped(event) {
   var cp= this.clickCount;   //here can get the clickCount
    this.stop = setInterval(function() {
        console.log(this.clickCount); //occur a undefined error
    }, 1000);
}

}

the error

2 Answers2

2

it is a scope problem, to solve it quickly, just do it:

startTapped(event) {
   var that = this;
   this.stop = setInterval(function() {
       console.log(that.clickCount); //no more undefined error
   }, 1000);
}

I happens because "this" inside the "setInterval" is the function "setInterval" it self, not the "this" of the scope of "startTapped", if you create a pointer to the "this", you can use that pointer inside "setInterval"

Adriano Spadoni
  • 4,540
  • 1
  • 25
  • 25
1

I don't know ionic but I think you should use arrow function/fat arrow as shown below,

this.stop = setInterval(()=> {
        console.log(this.clickCount); //this will log this.clickCount
    }, 1000);
}

You can check this answer with arrow function and without arrow function. But no Ionic. sorry for that.

micronyks
  • 54,797
  • 15
  • 112
  • 146