use*_*303 2 javascript typescript ionic2 ionic3 angular
我想每1秒运行一次功能.搜索后,我发现setInterval但它对我不起作用.
setInterval(function(){
this.myfuntion();
}, 1000);
Run Code Online (Sandbox Code Playgroud)
我也试过,this.myfuntion但它也不起作用.
seb*_*ras 11
解决方案是使用Arrow函数:
setInterval(() => {
this.myfuntion(); // Now the "this" still references the component
}, 1000);
Run Code Online (Sandbox Code Playgroud)
使用箭头函数时,this不会覆盖该属性,仍会引用该组件实例.
基本上有两种方法可以执行此操作。
尝试使用最适合您需求的可观察的。
方法1:
import {Observable} from 'Rxjs/rx';
import { Subscription } from "rxjs/Subscription";
// if you want your code to work everytime even though you leave the page
Observable.interval(1000).subscribe(()=>{
this.functionYouWantToCall();
});
Run Code Online (Sandbox Code Playgroud)
方法2:
// if you want your code to work only for this page
//define this before constructor
observableVar: Subscription;
this.observableVar = Observable.interval(1000).subscribe(()=>{
this.functionYouWantToCall();
});
ionViewDidLeave(){
this.observableVar.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
尝试这个。我认为这是一个范围问题。不绑定 setInterval 中的范围转到窗口对象
setInterval(function(){ this.myfunction();}.bind(this), 1000);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10915 次 |
| 最近记录: |