4
votes

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
queryparams is deprecated, you shouldn't be using this Two older properties are still available, however, their replacements are preferable as they may be deprecated in a future Angular version.Liam
The ActivatedRoute is nulled out when the route is destroyed, so there is no need to manually unsubscribe.Andrei Gătej

2 Answers

2
votes

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.

0
votes

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