离子2:设定间隔

V. *_*vet 6 javascript typescript ionic2 ionic3 angular

我尝试在.ts文件中设置一个间隔,但我不明白如何在间隔中的同一文件中使用一个函数.

解释 :

我的间隔设置:

this.task = setInterval(function () {
            this.refreshData();
        }, 300);
Run Code Online (Sandbox Code Playgroud)

我的功能在同一个ts文件中:

refreshData() : void{
        console.log('update...');
    }
Run Code Online (Sandbox Code Playgroud)

当我在我的设备上运行时,我有这个错误:

04-19 10:38:57.535 21374-21374/com.ionicframework.app722890 I/chromium: [INFO:CONSOLE(79432)] "TypeError: this.refreshData is not a function
                                                                                      at file:///android_asset/www/build/main.js:10987:18
                                                                                      at t.invokeTask (file:///android_asset/www/build/polyfills.js:3:10284)
                                                                                      at Object.onInvokeTask (file:///android_asset/www/build/main.js:39626:37)
                                                                                      at t.invokeTask (file:///android_asset/www/build/polyfills.js:3:10220)
                                                                                      at e.runTask (file:///android_asset/www/build/polyfills.js:3:7637)
                                                                                      at invoke (file:///android_asset/www/build/polyfills.js:3:11397)
                                                                                      at e.args.(anonymous function) (file:///android_asset/www/build/polyfills.js:2:30193)", source: file:///android_asset/www/build/main.js (79432)
Run Code Online (Sandbox Code Playgroud)

我尝试这种方式,但我不工作:

this.task = setInterval(this.refreshData(), 300);
Run Code Online (Sandbox Code Playgroud)

这只调用我的函数一次.

有人有想法吗?

Tie*_*han 21

使用箭头功能

this.task = setInterval(() => {
  this.refreshData();
}, 300);
Run Code Online (Sandbox Code Playgroud)

或者像这样存储上下文

let self = this;
this.task = setInterval(function () {
  self.refreshData();
}, 300);
Run Code Online (Sandbox Code Playgroud)

或使用 bind

this.task = setInterval((function () {
  this.refreshData();
}).bind(this), 300);
Run Code Online (Sandbox Code Playgroud)

如果只有一个函数调用:

this.task = setInterval(this.refreshData.bind(this), 300);
Run Code Online (Sandbox Code Playgroud)

你可以通过https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch1.md了解更多相关信息.