Ionic2函数setInterval无法获取参数

Ionic2 function setInterval can't get a parameter

我使用 Ionic2 构建了一个基于 Angular2 和 Cordova 的应用程序。 当我使用函数 setInterval 获取一个名为 clickCount 的参数时,发生了一个未定义的错误。

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

}

我不知道 ionic 但我认为你应该使用 arrow function/fat arrow 如下所示,

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

您可以使用 arrow function 和不使用 arrow function 检查此答案。但没有离子。对不起。

这是一个范围问题,要快速解决,就这样做:

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

我碰巧是因为 "setInterval" 里面的 "this" 是函数 "setInterval" 它自己,而不是 "startTapped" 范围的 "this",如果你创建指向 "this" 的指针,您可以在 "setInterval"

中使用该指针