Ionic2函数setInterval无法获取参数 [英] Ionic2 function setInterval can't get a parameter

查看:109
本文介绍了Ionic2函数setInterval无法获取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Ionic2构建一个基于Angular2和Cordova的应用程序。
当我使用功能的setInterval得到一个称为的clickCount参数,它occurt一个取消定义错误。

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

我发生了因为setInterval中的this是函数setInterval 它自己,而不是startTapped范围的this,如果你创建一个指向this的指针,你可以在setInterval里面使用那个指针

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"

这篇关于Ionic2函数setInterval无法获取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆