Do you need to unsubscribe from a subscription to router params in Angular?

Viewed 741

When you subscribe to query params in a component, do you need to unsubscribe? I'm trying to avoid a memory leak.

Subscription with variable for unsubscribe()

  subscription$: Subscription

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.subscription$ = this.route.queryParams.subscribe(
      (params: any): void => {
        // ... Do stuff here ...
      }
    )
  }

  ngOnDestroy() {
    if (this.subscription$ !== undefined || this.subscription$ !== null) {
      this.subscription$.unsubscribe()
    }
  }

Subscription without variable for unsubscribe()


  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.queryParams.subscribe(
      (params: any): void => {
        // ... Do stuff here ...
      }
    )
  }

Which one is a better solution?

2 Answers

The ActivatedRoute unsubscribes all of its subscribers when the component is destroyed.

You can look the doc: https://angular.io/guide/router#!#reuse

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.

You can found this question for reference

Angular is it necessary to unsubscribe from this.activatedRoute subscriptions

but i would say unsubscribing whenever you have subscribed to something is always a good practice. Their are various ways for unsubscribing we can do that just using only one extra variable for subscription

I always prefer to unsubscribe in this situation as well

Related