How to detect a route change in Angular?
Answers (2)
Add AnswerYou 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) }); } }
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); } }); } }