2017-02-17 17 views
2

内部でsetIntervalを使用しようとしています:class SignupComponent function(){}は、function(){}のスコープ外のクラスの2つの変数SignupComponentクラスと私は失敗します。私はサイクルでいくつかのアニメーションをアクティブにできるように私はsetIntervalを使用しています。ここ コードである:角度2内でsetInterval関数を使用するコンポーネント

export class SignupComponent { 
     state = 'normal'; 
     state2 = 'normal'; 
     v1 = 0; 
     myFunc = function (p1){setInterval(function(){ 
      p1++; 
      if (p1%4==0) 
     { 
      console.log(this.state2); 
      this.state == 'normal' ? this.state = 'disappear': this.state 
       = 'normal'; 
      this.state2 == 'normal' ? this.state2 = 'appear': this.state2 
       = 'normal' 
     } 
    }, 1000)}; 

問題はthis.state、内部のsetInterval this.state2(関数(){...} 状態を参照しないで、範囲外の彼であるSTATE2私はこの閉鎖を行うことができない理由クラスのスコープ。? は、値が更新されますので、VARSのそれらのカップルを接続する方法はありますか?

答えて

1

ちょうどthisを作るために矢印機能() => {}代わりfunction() {}のを使用します現在のクラスインスタンスをポイントします

myFunc = function (p1){setInterval(() => { 
2

のsetTimeout /のsetInterval(角ユーザーのために)、このように呼ばれるべきです。

export class demo implements OnDestroy{ 
    private _setTimeoutHandler: any; 
    private _setIntervalHandler: any; 

    mymethod1(){ 
     this._setTimeoutHandler = setTimeout(() => { 
     // my to do 
     }, 100); 
    } 

    mymethod2(){ 
     this._setIntervalHandler = setInterval(() => { 
      myTimer() 
    }, 100); 
    } 


    ngOnDestroy() { 
     clearTimeout(this._setTimeoutHandler)} 
     clearInterval(this.__setIntervalHandler); 
    } 
} 
関連する問題