【发布时间】:2018-07-30 16:55:22
【问题描述】:
我遇到了这个关于如何使用 takeUntil() 停止订阅的答案 Angular/RxJs When should I unsubscribe from `Subscription`。答案还指出
秘诀(正如@metamaker 已经指出的)是在我们每个 .subscribe() 调用之前调用 .takeUntil(this.ngUnsubscribe) ,这将保证在组件被销毁时所有订阅都将被清除。
但是,我无法理解为什么我的两个示例之一不会停止订阅。 Here is a working example
我的服务:
export class GpsService {
gps: Observable<any>;
private ngUnsubscribe: Subject<any> = new Subject<any>();
constructor() { }
startFakeGps = (): void => {
// This example does not stop the subscription after calling stopGps().
this.gps = Observable.timer(3000, 1000);
this.gps.takeUntil(this.ngUnsubscribe);
// This example stops the subscription after calling stopGps().
// this.gps = Observable.timer(3000, 1000).takeUntil(this.ngUnsubscribe);
}
stopGps() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
我的组件:
export class ButtonOverviewExample implements OnInit {
constructor(private gspService: GpsService){
}
ngOnInit(){
this.gspService.startFakeGps();
this.gspService.gps.subscribe(data => {});
}
// stop gps after clicking a button
stopGps(){
this.gspService.stopGps();
}
}
示例 1:
// This example does not stop the subscription after calling stopGps().
this.gps = Observable.timer(3000, 1000);
this.gps.takeUntil(this.ngUnsubscribe);
示例 2:
// This example stops the subscription after calling stopGps().
this.gps = Observable.timer(3000, 1000).takeUntil(this.ngUnsubscribe);
我认为这两个示例在实际订阅开始之前都使用了takeUntil(),并且它们是相同的。为什么这些示例的行为不同?我错过了什么?
【问题讨论】:
标签: angular observable