For Angular 4+
If you put the following code in parent or top-level components like AppComponent then this will not work. It only works on child or lower-level components for which you have defined user route data:
public constructor(private route:ActivatedRoute, private router:Router) { console.log(route.snapshot.data['title']); }
So, if you want to access user-generated route data globally from a parent or top-level component, in order to gain access to change user-generated route data, you must listen to router events, especially the RoutesRecognized or NavigationEnd events. I am going to show two procedures with an AppComponent with two events:
First approach:
export class AppComponent implements OnInit, AfterViewInit { constructor(private activatedRoute: ActivatedRoute, private router: Router) { } ngOnInit() { this.router .events .filter(event => event instanceof NavigationEnd) .map(() => { let child = this.activatedRoute.firstChild; while (child) { if (child.firstChild) { child = child.firstChild; } else if (child.snapshot.data && child.snapshot.data['custom_data']) { return child.snapshot.data['custom_data']; } else { return null; } } return null; }).subscribe( (customData: any) => { console.log(customData); }); } }
The second approach uses:
this.router.events .filter(event => event instanceof RoutesRecognized) .map( (event: RoutesRecognized) => { return event.state.root.firstChild.data['custom_data']; }) .subscribe(customData => { console.log(customData); });
Note. . Although the last one is shorter and usually works, but if you have nested routes, it is recommended to use the first one.
source share