I am trying to get the parent route params in a lazy loaded route component, however using activatedRoute.parent.params
does not seem to work? I have a snippet which does actually work, however it involves using a 'magic' array index number to retrieve the value....
Why is this the case and is there a cleaner method in which I don't have to retrieve an array value (this.activatedRoute.pathFromRoot[1]
)?
I have the following route in which I lazy load a module:
parent.route
routes:Routes = [
{
path: "dashboard/:id",
component: dashboard.DashboardComponent,
canActivate: [guard.LoggedInGuard],
children: [
{
path: "my-dock",
loadChildren: 'path/child.module#Child'
}
]
}
];
Then in the default component for child.module
I have the following:
child.component
ngOnInit() {
this.activatedRoute.pathFromRoot[1].params.subscribe((params: Params) => {
console.log(params); // returns {id: "123456789"}
});
this.activatedRoute.parent.params.subscribe((params: Params) => {
console.log(params); // returns {}
});
}
Why can't I use this.activatedRoute.parent.params
to get the id
param?
Well you can access parent of parent router data. It seems a bit weird in some project structures but you can do it if you are aware of your router structure.
constructor(
private route: ActivatedRoute
)
this.route.parent.parent.params.subscribe( (params) => {
console.log(params);
this.urlKey = params['urlKey'];
});
The following methods are working perfectly in Angular-6 (may be in Angular-5, but not sure)
// method 1
this.activatedRoute.pathFromRoot[1].params.subscribe((params: Params) => {
console.log(params);
});
// method 2
this.activatedRoute.parent.params.subscribe((params: Params) => {
console.log(params);
});
Q. Why can't I use this.activatedRoute.parent.params to get the id param?
A. You have not mentioned the Angular version you were using but in Angular-6 both these methods work.
The best way to get this done without the 'magic' array index number
is to use a Service .
ParentComponent
constructor(private router : Router){
this.service.setParams(this.router.url);//you might need to split here
//you can also make use of Activate Route and subcribe to params
}
Service
params:string;
setParams(params:string){
this.params = params;
}
getparams(){
return this.params;
}
Now in child Lazyloaded component you can get the params using service.getparams()
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