2017-07-21 195 views
1

我用下面的代碼計時器:如何取消訂閱/停止Observable?

export class TimerService { 
    private ticks: number = 0; 
    private seconds: number = 0; 
    private timer; 

    constructor(seconds: number) { 
    this.seconds = seconds; 
    this.timer = Observable.timer(2000, 1000); 
    this.timer.subscribe(t => { 
     this.ticks = t; 
     this.disactivate(); 
    }); 
    } 

    private disactivate() { 
    if (this.ticks === this.seconds) { 
     this.timer.dispose(); 
    } 
    } 
} 

當我嘗試在網上停止定時器:

this.timer.dispose(); // this.timer.unsubscribe(); 

它不工作對我來說

+0

你想要什麼用這個存檔? –

+0

我需要停止計時器並以秒爲單位修復最後的計時器時間。 – OPV

回答

5

subscribe方法返回一個Subscription對象,您稍後可以使用它來停止監聽您訂閱的observable所包含的流。

import { ISubscription } from 'rxjs/Subscription': 
import { TimerObservable } from 'rxjs/observable/TimerObservable'; 

export class TimerService { 
    private ticks = 0; 
    private timer$: TimerObservable; 
    private $timer : ISubscription; 

    constructor(private seconds = 0) { 
    this.timer$ = TimerObservable.create(2000, 1000);//or you can use the constructor method 
    this.$timer = this.timer.subscribe(t => { 
     this.ticks = t; 
     this.disactivate(); 
    }); 
    } 

    private disactivate() { 
    if (this.ticks >= this.seconds) { 
     this.$timer.unsubscribe(); 
    } 
    } 
} 

它重要注意到unsubscribe存在rxjs(第5版及以上),在此之前,RX(版本低於5,不同的封裝)的方法被稱爲dispose

+0

你可以評論解決方案嗎?什麼是'this。$ timer'? – OPV

+0

只是訂閱的命名約定,而'timer $'是Observables –