我应该何时存储Subscription实例并unsubscribe()在NgOnDestroy生命周期中调用,何时可以忽略它们?
保存所有订阅会在组件代码中引入很多混乱.
HTTP客户端指南忽略这样的订阅:
getHeroes() {
this.heroService.getHeroes()
.subscribe(
heroes => this.heroes = heroes,
error => this.errorMessage = <any>error);
}
Run Code Online (Sandbox Code Playgroud)
同时," 航线与导航指南"说:
最终,我们会在其他地方导航.路由器将从DOM中删除此组件并将其销毁.在此之前我们需要自己清理.具体来说,我们必须在Angular破坏组件之前取消订阅.如果不这样做可能会造成内存泄漏.
我们取消订阅我们
Observable的ngOnDestroy方法.
private sub: any;
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = +params['id']; // (+) converts string 'id' to a number
this.service.getHero(id).then(hero => this.hero = hero);
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud) subscription observable rxjs angular angular-component-life-cycle
tl; dr:基本上我想将Angular ngOnDestroy与Rxjs takeUntil()运算符结合起来. - 那可能吗?
我有一个Angular组件,可以打开几个Rxjs订阅.当组件被销毁时,需要关闭它们.
一个简单的解决方案是:
class myComponent {
private subscriptionA;
private subscriptionB;
private subscriptionC;
constructor(
private serviceA: ServiceA,
private serviceB: ServiceB,
private serviceC: ServiceC) {}
ngOnInit() {
this.subscriptionA = this.serviceA.subscribe(...);
this.subscriptionB = this.serviceB.subscribe(...);
this.subscriptionC = this.serviceC.subscribe(...);
}
ngOnDestroy() {
this.subscriptionA.unsubscribe();
this.subscriptionB.unsubscribe();
this.subscriptionC.unsubscribe();
}
}
Run Code Online (Sandbox Code Playgroud)
这有效,但有点多余.我特别不喜欢那样 - 这unsubscribe()是其他地方,所以你必须记住这些是相互关联的. - 组件状态受订阅污染.
我更喜欢使用takeUntil()运算符或类似的东西,使它看起来像这样:
class myComponent {
constructor(
private serviceA: ServiceA,
private serviceB: ServiceB,
private serviceC: ServiceC) {}
ngOnInit() {
const destroy = Observable.fromEvent(???).first();
this.subscriptionA …Run Code Online (Sandbox Code Playgroud) angular ×2
rxjs ×2
angular-component-life-cycle ×1
components ×1
observable ×1
rxjs5 ×1
subscription ×1