Ionic 2 : Set interval(离子2:设置间隔)
问题描述
我尝试在 .ts 文件中设置间隔,但我不明白如何在间隔中使用同一文件中的函数.
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.
解释一下:
我的间隔设置:
this.task = setInterval(function () {
this.refreshData();
}, 300);
和我的函数在同一个 ts 文件中:
And my function in the same ts file :
refreshData() : void{
console.log('update...');
}
当我在我的设备上运行时,我遇到了这个错误:
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);
这只会调用我的函数一次.
This call my function only one time.
有人有想法吗?
推荐答案
使用箭头函数
this.task = setInterval(() => {
this.refreshData();
}, 300);
或像这样存储上下文
let self = this;
this.task = setInterval(function () {
self.refreshData();
}, 300);
或使用绑定
this.task = setInterval((function () {
this.refreshData();
}).bind(this), 300);
如果只有一个函数调用:
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
这篇关于离子2:设置间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:离子2:设置间隔


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01