• 118489

    文章

  • 803

    评论

  • 12

    友链

  • 最近新加了换肤功能,大家多来逛逛吧~~~~
  • 喜欢这个网站的朋友可以加一下QQ群,我们一起交流技术。

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: 同时,《 路线与导航指南 》指出:

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

695856371Web网页设计师②群 | 喜欢本站的朋友可以收藏本站,或者加入我们大家一起来交流技术!

0条评论

Loading...


自定义皮肤 主体内容背景
打开支付宝扫码付款购买视频教程
遇到问题联系客服QQ:419400980
注册梁钟霖个人博客