Angular 2.0, how to detect route change on child component
Create a global service that subscribes to router
and inject the service wherever you want to know about route changes. The service can expose changes by an Observable
itself so interested components also can subscribe to get notified automatically.
RC3+ solution:
constructor(private router: Router) {
router.events.subscribe(event => {
if (event.constructor.name === 'NavigationStart') {
console.log(event.url);
}
});
}
Alternatively, you can filter for the NavigationStart
event using the filter
pipe (RxJS 6+):
constructor(private router: Router) {
router.events.pipe(
filter(event => event instanceof NavigationStart),
).subscribe((event: NavigationStart) => {
console.log(event.url);
});
}