简体   繁体   English

Ionic2函数setInterval无法获取参数

[英]Ionic2 function setInterval can't get a parameter

I use Ionic2 to build an app,which based on Angular2 and Cordova. 我使用Ionic2构建一个基于Angular2和Cordova的应用程序。 when I use function setInterval to get a parameter called clickCount,it occurt an undefine error. 当我使用函数setInterval来获取一个名为clickCount的参数时,它会发出一个undefine错误。

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" 我发生的原因是“setInterval”里面的“this”是函数“setInterval”它自己,而不是“startTapped”范围的“this”,如果你创建一个指向“this”的指针,你可以在里面使用那个指针“的setInterval”

I don't know ionic but I think you should use arrow function/fat arrow as shown below, 我不知道ionic但我认为你应该使用arrow function/fat arrow ,如下所示,

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 . 您可以使用arrow function和没有arrow function来检查此答案。 But no Ionic. 但没有离子。 sorry for that. 对不起

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM