2016-09-18 6 views
7

私は5秒ごとにGET要求を送信するタイマーを作成しようとしていますが、私はそれを行うことができますが、私は別のページ(ルーティング)私はngOnDestroyを追加しようとしましたが、私は "退会" 方法Angular2:タイマーの作成と破棄

import {Component, OnInit, OnDestroy} from '@angular/core'; 
 
import {Observable} from 'rxjs/Rx'; 
 

 
@Component({ 
 
    templateUrl: 'app/pages/CurrentRuns/currentruns.component.html' 
 
}) 
 

 

 

 

 
export class CurrentRunsComponent implements OnInit, OnDestroy { 
 
    private timer; 
 
    ticks=0; 
 
    
 

 
    ngOnInit() { 
 
    this.timer = Observable.timer(2000,5000); 
 
    this.timer.subscribe(t => this.tickerFunc(t)); 
 
    } 
 
    tickerFunc(tick){ 
 
    console.log(this); 
 
    this.ticks = tick 
 
    } 
 

 
    ngOnDestroy(){ 
 
    console.log("Destroy timer"); 
 

 
    } 
 
} 
 

 
私はangular2のRC7を使用しています

を持っていない、 "rxjs": "5.0.0-beta.12"

答えて

19

observableを購読すると、サブスクリプションオブジェクトが返されます

import {Component, OnInit, OnDestroy} from '@angular/core'; 
 
import { Observable, Subscription } from 'rxjs/Rx'; 
 

 
@Component({ 
 
    templateUrl: 'app/pages/CurrentRuns/currentruns.component.html' 
 
}) 
 
export class CurrentRunsComponent implements OnInit, OnDestroy { 
 
    ticks = 0; 
 
    private timer; 
 
    // Subscription object 
 
    private sub: Subscription; 
 

 
    ngOnInit() { 
 
     this.timer = Observable.timer(2000,5000); 
 
     // subscribing to a observable returns a subscription object 
 
     this.sub = this.timer.subscribe(t => this.tickerFunc(t)); 
 
    } 
 
    tickerFunc(tick){ 
 
     console.log(this); 
 
     this.ticks = tick 
 
    } 
 

 
    ngOnDestroy(){ 
 
     console.log("Destroy timer"); 
 
     // unsubscribe here 
 
     this.sub.unsubscribe(); 
 

 
    } 
 
}

+0

こんにちは、私は、一つの問題を持っています。 –

1

単にあなたはmyObservablesubscribe()によって返されるオブジェクトである

ngOnDestroy() { 
    this.myObservable.unsubscribe(); 
} 

を解除する必要があります。

refrence:私はそれを停止しますが、私は戻ってこのページに来たときに2つのタイマーが起動する別のページに訪問したときにangular2 - Best way to terminate a observable interval when path changes

+1

あなたはthis.timer.unsubscribe();という意味ですか? - 私は退会していないので(); this.timerと入力します。 –

+1

変数を作成 "private subscriberObj:Subscription;"次いで とを割り当てる "this.subscriberObj = this.timer.subscribe(T => this.tickerFunc(T));" そして最後に "ngOnDestroy(){this.subscriberObj .unsubscribe();}" –

+0

おかげ!!!上記の完全なコードがうまくいっています! –

関連する問題