本文介紹了離子2:設(shè)置間隔的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我嘗試在 .ts 文件中設(shè)置間隔,但我不明白如何在間隔中使用同一文件中的函數(shù).
I try to set an interval in a .ts file but I don't understand how to use a function in the same file in the interval.
解釋一下:
我的間隔設(shè)置:
this.task = setInterval(function () {
this.refreshData();
}, 300);
和我的函數(shù)在同一個(gè) ts 文件中:
And my function in the same ts file :
refreshData() : void{
console.log('update...');
}
當(dāng)我在我的設(shè)備上運(yùn)行時(shí),我遇到了這個(gè)錯(cuò)誤:
When I run on my device, I have this error :
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)
我嘗試這種方式但我不工作:
I try this way but I doesn't work :
this.task = setInterval(this.refreshData(), 300);
這只會(huì)調(diào)用我的函數(shù)一次.
This call my function only one time.
有人有想法嗎?
推薦答案
使用箭頭函數(shù)
this.task = setInterval(() => {
this.refreshData();
}, 300);
或像這樣存儲(chǔ)上下文
let self = this;
this.task = setInterval(function () {
self.refreshData();
}, 300);
或使用綁定
this.task = setInterval((function () {
this.refreshData();
}).bind(this), 300);
如果只有一個(gè)函數(shù)調(diào)用:
if only one function call:
this.task = setInterval(this.refreshData.bind(this), 300);
您可以通過 https://github.com/getify/You-Dont-Know-JS/tree/1st-ed/this%20%26%20object%20prototypes/ch1.md
這篇關(guān)于離子2:設(shè)置間隔的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!