私は1秒ごとに機能を実行したいと思います。検索後、私はsetInterval
を見つけましたが、それは私のためには機能しません。ION 3のsetInterval
setInterval(function(){
this.myfuntion();
}, 1000);
私もthis.myfuntion
を試してみましたが、それはあまりにも動作しません。
私は1秒ごとに機能を実行したいと思います。検索後、私はsetInterval
を見つけましたが、それは私のためには機能しません。ION 3のsetInterval
setInterval(function(){
this.myfuntion();
}, 1000);
私もthis.myfuntion
を試してみましたが、それはあまりにも動作しません。
これを試してください。スコープの問題だと思う。 setIntervalでスコープを結合するウィンドウオブジェクト
setInterval(function(){ this.myfunction();}.bind(this), 1000);
に行くことなく、解決策は、Arrow functionsを使用することです:
setInterval(() => {
this.myfuntion(); // Now the "this" still references the component
}, 1000);
矢印機能を使用する場合は、this
プロパティが上書きされず、まだ言及コンポーネントインスタンス
基本的に2つの方法があります。
あなたの要件に最も適した観察可能なものをお試しください。
方法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();
});
方法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();
}