2017-07-21 114 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 –