我应该何时存储Subscription实例并unsubscribe()在NgOnDestroy生命周期中调用,何时可以忽略它们?
保存所有订阅会在组件代码中引入很多混乱.
HTTP客户端指南忽略这样的订阅:
getHeroes() {
  this.heroService.getHeroes()
                   .subscribe(
                     heroes => this.heroes = heroes,
                     error =>  this.errorMessage = <any>error);
}
同时," 航线与导航指南"说:
最终,我们会在其他地方导航.路由器将从DOM中删除此组件并将其销毁.在此之前我们需要自己清理.具体来说,我们必须在Angular破坏组件之前取消订阅.如果不这样做可能会造成内存泄漏.
我们取消订阅我们
Observable的ngOnDestroy方法.
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();
}
subscription observable rxjs angular angular-component-life-cycle