Angular 9 unsubscribe NavigationEnd

Viewed 1643

I'm using a subscription on router NavigationEnd like this:

this.router.events
  .subscribe((event) => {
    if (event instanceof NavigationEnd) {
      this.getData();
    }
  });

I need this to update the page data when navigating in the same route e.g. /product1 and /product2 uses the same component and route and is handled in a custom route service

This is for getting data when the route updates in the same component, and it works as expected

The problem is that this.getData() also runs when navigating to another component, this creates a lot of problems in the component I navigate to, and I also run a unnecessary get from the server

So the question is: Can I unsubscribe to the router when navigating away from the component so this.getData() don't run?

1 Answers

You can use Subscription in Observables

First of all initialize on your component

navigationSubs = new Subscription();


this.navigationSubs = this.router.events
  .subscribe((event) => {
    if (event instanceof NavigationEnd) {
      this.getData();
    }
  });

On destroy or whenever you want

this.navigationSubs.unsubscribe();
Related