Trying to access the route params from your root component is not feasible since it lacks a defined route.
I can propose two solutions to resolve this issue:
1. Manually parse the params (not very reliable)
ngOnInit() {
this.router.events
.pipe(
filter(e => e instanceof NavigationEnd),
map((e: NavigationEnd) => e.urlAfterRedirects),
// parse the url as required
)
.subscribe();
}
2. Utilize a dedicated service to share the params (more complex)
Develop a service (named RouteParamsService
in this example) to store the current ids. Then access the id within your AppComponent
.
HeroComponent
constructor(private route: ActivatedRoute,
private paramsService: RouteParamsService) {
}
ngOnInit() {
this.route.paramMap.subscribe(params => this.paramsService.set('heroId', params.get('id')));
}
ngOnDestroy() {
this.paramsService.delete('heroId');
}
AppComponent
constructor(private paramsService: RouteParamsService) {
}
ngOnInit() {
this.paramsService.params.subscribe(params => params['heroId']);
}