Get parent route parameters from component with lazy loaded route

I am trying to get the parent route parameters in a lazy loaded component of the route, however using activatedRoute.parent.params doesn't seem to work? I have a snippet that really works, but it involves using the "magic" array index number to retrieve the value ....

Why is this so, and is there a cleaner method in which I do not need to retrieve the value of the array ( this.activatedRoute.pathFromRoot[1] )?


I have the following route where I lazy load the 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 parameter?

+8
angular typescript
source share
3 answers

The best way to do this without the 'magic' array index number is to use the Service.

  • get Params or the parent url and put them in the service.
  • Access to parameters from a service variable in the Lazy component from a service. Something like that

Parent parent

 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 the Lazyloaded child component you can get parameters using service.getparams()

+1
source share

What do you get when you do this?

 constructor(private route: ActivatedRoute) { this.route.params.subscribe(params => console.log(params)); } 

Alternatively, you can check the snapshot key on the route object. It's hard to get a clear idea with this little code.

0
source share

Well, you can access the parent data of the parent router. In some project structures this is a little strange, but you can do it if you know about your router structure.

  constructor( private route: ActivatedRoute ) this.route.parent.parent.params.subscribe( (params) => { console.log(params); this.urlKey = params['urlKey']; }); 
0
source share

All Articles