问题:
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:同时Route & Navigation Guide说:
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://en.stackoom.com/question/2ZThe参考二: https://stackoom.com/question/2ZThe