我将以下代码用于计时器:
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 :(得分:12)
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
答案 1 :(得分:0)
最好的方法是在实例销毁时退订。
ngOnDestroy() {
this.sub.unsubscribe();
}
答案 2 :(得分:0)
因此,在进行了一些惩罚研究之后,我为这个问题添加了自己的npm库。
Improves previous answer by NOT having to add any extra convolution variables and ease of use.
答案 3 :(得分:0)
我还没有使用过计时器,但我认为这个概念仍然有效。我使用的方法是使用服务。
new BehaviorSubject<T>(T)
。new Subscription()
对象。addSubscription
方法包装订阅。ngOnDestroy(): void
取消订阅服务
private organisation = new BehaviorSubject<__Organisation>(newOrganisation);
organisation$ = this.organisation.asObservable();
private organisationSubscription: Subscription = new Subscription();
服务方式
addOrganisationSubscription(subscription: Subscription): void {
this.organisationSubscription.add(subscription);
}
unSubscribeOrganisation(): void {
this.organisationSubscription.unsubscribe();
}
addOrganisationSubscription(subscription: Subscription): void {
this.organisationSubscription.add(subscription);
}
组件
this.organisationService.addOrganisationSubscription(
this.organisationService.organisation$.subscribe(
...
)
)
ngOnDestroy(): void {
this.organisationService.unSubscribeOrganisation();
}