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