问题:
When should I store the Subscription
instances and invoke unsubscribe()
during the NgOnDestroy life cycle and when can I simply ignore them? 在NgOnDestroy生命周期中,什么时候应该存储Subscription
实例并调用unsubscribe()
?什么时候可以忽略它们?
Saving all subscriptions introduces a lot of mess into component code. 保存所有订阅会在组件代码中带来很多麻烦。
HTTP Client Guide ignore subscriptions like this: HTTP客户端指南会忽略这样的订阅:
getHeroes() {
this.heroService.getHeroes()
.subscribe(
heroes => this.heroes = heroes,
error => this.errorMessage = <any>error);
}
In the same time Route & Navigation Guide says that: 同时,《 路线与导航指南 》指出:
Eventually, we'll navigate somewhere else. 最终,我们将导航到其他地方。 The router will remove this component from the DOM and destroy it. 路由器将从DOM中删除此组件并销毁它。 We need to clean up after ourselves before that happens. 我们需要在此之前进行自我清理。 Specifically, we must unsubscribe before Angular destroys the component. 具体来说,我们必须在Angular销毁组件之前取消订阅。 Failure to do so could create a memory leak. 否则可能会导致内存泄漏。
We unsubscribe from our
Observable
in thengOnDestroy
method. 我们通过ngOnDestroy
方法取消订阅Observable
。
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();
}
解决方案:
参考一: https://stackoom.com/question/2ZThe/Angular-RxJs我应该何时退订-Subscription参考二: https://oldbug.net/q/2ZThe/Angular-RxJs-When-should-I-unsubscribe-from-Subscription
来源:oschina
链接:https://my.oschina.net/u/4428122/blog/4358489