How to detect a route change in Angular?

Forums AngularHow to detect a route change in Angular?
Staff asked 2 years ago

Answers (2)

Add Answer
Staff answered 2 years ago

You can subscribe (Rx event) to a Router instance in Angular. As a result, you can do things like

class yourClass {
  constructor(private router: Router) {
    router.subscribe((val) => /*your logic*/)
  }
}

Edit 2:
see also: Router. events doc

class yourClass {
  constructor(private router: Router) {
    router.events.subscribe((val) => {
        // see also 
        console.log(val instanceof NavigationEnd) 
    });
  }
}

 

Staff answered 2 years ago

To detect route changes subscribe route in constructor.

import { Router, Event, NavigationStart, NavigationEnd, NavigationError } from ‘@angular/router’;

 

class AppComponent {

constructor(private router: Router) {

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

if (event instanceof NavigationEnd) {
// Hide loading indicator
}

if (event instanceof NavigationError) {
// Hide loading indicator

// Present error to user
console.log(event.error);
}
});

}
}

 

Subscribe

Select Categories