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

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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With