Angular / RxJs我应该何时退订`Subscription`

左心房为你撑大大i 提交于 2020-08-04 19:13:15

问题:

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 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://stackoom.com/question/2ZThe/Angular-RxJs我应该何时退订-Subscription
参考二: https://oldbug.net/q/2ZThe/Angular-RxJs-When-should-I-unsubscribe-from-Subscription
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!