[Fixed] Angular: How to detect route changes in current component?

Issue

I want to detect a route from the current component and tried something like that. But it is triggered on every route starts and ends. Instead of this, how can I detect only the route changes when routes from this DetailsComponent?

export class DetailsComponent {

    constructor(private router: Router) {

        this.router.events.subscribe((event: Event) => {
            if (event instanceof NavigationStart) {
            }

            if (event instanceof NavigationEnd) {
            }
        });

   }
}

I need to get the url while navigation from this DetailsComponent and make an operation if the url is not /employees.

Solution

The reason your events continue to be detected, is because you are not unsubscribing from router.events when your DetailsComponent is destroyed.

If you simply unsubscribe, it should work for you:

export class DetailsComponent {
  private sub = this.router.events
    .pipe(
      filter(event => event instanceof NavigationStart),
      map(event => event as NavigationStart),  // appease typescript
      filter(event => event.url !== '/employees')
    )
    .subscribe(
      event => console.log('[DetailsComponent] NOT going to "/employees"!', event)
    );

  constructor(private router: Router) { }

  ngOnDestroy() {
    console.log('>> STOP listening to events for DetailsComponent');
    this.sub.unsubscribe();
  }

}

Here’s a StackBlitz example.

Leave a Reply

(*) Required, Your email will not be published