How can I detect a route change on a child component?. This is what I have tried, but I only see the app component trace the route change. I want to be able to detect when the url change from e.g. #/meta/a/b/c to #/meta/a/b/c/d in the MetaDetailView component.
@RouteConfig([
{ path: '/', name: 'Home', redirectTo: ['Meta']},
{ path: '/meta/...', name: 'Meta', component: MetaMainComponent, useAsDefault: true},
...other routes...,
])
export class AppComponent {
constructor(private _router: Router) {
_router.subscribe( (url) => console.log("app.url = " + url));
}
}
@RouteConfig([
{ path: '/*other', name: 'Detail', component: MetaDetailViewComponent, useAsDefault: true},
])
export class MetaMainComponent {
constructor(private _router: Router) {
_router.subscribe( (url) => console.log("metamain.url = " + url));
console.log("MetaMainComponent")
}
}
export class MetaDetailViewComponent {
constructor(private _router: Router) {
_router.subscribe( (url) => console.log("metadetail.url = " + url));
console.log("MetaDetailViewComponent")
}
}
Thanks Jesper
Steps to detect route change in Angular application Urls. Import Router, Event, NavigationStart, NavigationEnd, NavigationError from '@angular/router'. And inject router in the constructor. Subscribe to the NavigationStart, NavigationEnd, NavigationError events of the router.
You can check the current route by injecting the Location object into your controller and checking the path() , like so: class MyController { constructor(private location:Location) {} ... location. path(); ... }
We can test routing in Angular by using RouterTestingModule instead of RouterModule to provide our routes. This uses a spy implementation of Location which doesn't trigger a request for a new URL but does let us know the target URL which we can use in our test specs.
RouterState and ActivatedRoute are similar to their snapshot counterparts except that they expose all the values as observables, which are great for dealing with values changing over time. Any component instantiated by the router can inject its ActivatedRoute.
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);
});
}
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.
You have root access from any child router:
_router.root.subscribe(route => console.log('route', route));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With