Joshua Michael Calafell
Joshua Michael Calafell

Reputation: 3107

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

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?

Upvotes: 5

Views: 1589

Answers (2)

Caro
Caro

Reputation: 650

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

You can look the doc: https://angular.io/guide/router-tutorial-toh#observable-parammap-and-component-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.

Upvotes: 4

Passionate Coder
Passionate Coder

Reputation: 7294

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

Upvotes: -1

Related Questions