Angular/RxJs 我什么时候应该取消订阅`Subscription` - Angular/RxJs When should I unsubscribe from `Subscription`

问题:

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 the ngOnDestroy 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章