Angular is it necessary to unsubscribe from this.activatedRoute subscriptions

天涯浪子 提交于 2020-12-12 17:13:30

问题


My code:

ngOnInit() {

  this.activatedRoute.params.subscribe((params: Params) => {
    // do stuff
  })

  this.activatedRoute.data.subscribe((data: any) => {
    // do stuff
  })

}

My question is ... do I need to unsubscribe from these in ngOnDestroy?

As a matter of habit I always unsub but not sure if it is necessary here.

thanks


回答1:


No, you don't need to unsubscribe from route observables

From the Documentation

When subscribing to an observable in a component, you almost always arrange to unsubscribe when the component is destroyed.

There are a few exceptional observables where this is not necessary. The ActivatedRoute observables are among the exceptions.

The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

Feel free to unsubscribe anyway. It is harmless and never a bad practice.




回答2:


I would rather unsubscribe all then control the exceptions. Seems easier to maintain.

Something like this

  ngOnInit() {
    this.subscriptions.push(
      this.activatedRoute.params.subscribe((params: Params) => {
        // do stuff
      }));

    this.subscriptions.push(
      this.activatedRoute.data.subscribe((data: any) => {
        // do stuff
      }));
  }

  ngOnDestroy() {
    this.subscriptions.forEach((subscription: Subscription) => {
      subscription.unsubscribe();
    });
  }

Please see the example here: https://stackblitz.com/edit/angular-unsubscribing-then-all?file=src/app/app.component.ts




回答3:


For activated routes observable is an exception, because The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

Source: Angular Doc




回答4:


Normally when your component destroys, all the subscribed observables get unsubscribe automatically with few exceptions. But activatedRoute is not one of it. When router exit from a routed component it will destroy the component along with the injected activatedRoute



来源:https://stackoverflow.com/questions/52006017/angular-is-it-necessary-to-unsubscribe-from-this-activatedroute-subscriptions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!