2016-04-13 7 views
6

私はAngular2の新機能ですので、些細な質問であれば謝ります。私は別のリンクをクリックすると間隔を止めることができない。このコンポーネントは3,5秒ごとにDBテーブルからデータをフェッチし、チャットとして使用されるため、100人のユーザーがいつでも追加できます。これはバックグラウンドで常に実行したくないので、私はrouteronDeactivate()機能を使用して、ユーザーが別のリンクにいるときに停止させることを考えました。Angular2 - routerOnDeactivate()で観測可能な停止/キャンセル/クリア

私は何か間違っていると思います。誰も私を助けることができますか?

export class FeedComponent { 

    public feeditems: Feed[]; 
    public timer; 


    constructor(private _feedService: FeedService) { 
    } 

    getArticlesJSON() { 

     console.log('getArticlesJSON'); 
     this._feedService.getFeedJSON() 
      .subscribe(
       data => this.feeditems = data, 
       err => console.log(err), 
       () => console.log('Completed') 
      ); 
    } 

    routerOnDeactivate() { 

     // this.timer.remove(); 
     // this.timer.dematerialize(); 
     // clearInterval(this.timer); 

     console.log('-- deactivate '); 
     // console.log('-- deactivate ' + JSON.stringify(this.timer)); 
    } 

    routerOnActivate() { 

     this.timer = Observable.timer(5000,3500); 
     this.timer.subscribe(() => { 
      this.getArticlesJSON(); 
     }); 

     console.log('++ activate ' + JSON.stringify(this.timer)); 
    } 
} 

答えて

19
routerOnActivate() { 
    this.timer = Observable.timer(5000,3500); 
    this.subscription = this.timer.subscribe(() => { 
    this.getArticlesJSON(); 
    }); 
} 

routerOnDeactivate() { 
    this.subscription.unsubscribe(); 
} 
+0

それは退会リセットタイマーがゼロにすることを意味するのでしょうか? – Daniel

+1

「ゼロ」とは何を意味するのか分かりません。これはObservableが '()=> {this.getArticlesJSON();} 'をもう呼び出さないことを意味します。 –

+0

通常、退会すると、タイマーはゼロになるか、またはゼロになりますか?後にタイマーカウンターをリセットする必要がありますか? – Daniel

関連する問題