I have a route: / app / project / 23 / views
Each part of the path is a child of the previous part, and all children are lazy loaded (not sure if the lazy loaded bit is here)
/app (root component) /project (child component of app, child route of app) /23 (route param 'projectId') /views (child component of project, child route of project)
I am trying to access the route parameter 'projectId' (in this case: 23)
Do the following:
constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.params.subscribe(params => { console.log('params:', params); }
Gives me an empty object for this.route.params
params: {}
However, by doing this:
constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.parent.parent.params.subscribe(params => { console.log('params:', params); }
Gives me what I'm looking for:
params: Object {projectId: "23"}
Since this is a child route, I need to specify this.route. parent.parent to get route parameters of (some) parent route?
Is there a better way to get the parameters from a complete route, because what happens if:
1) I change the depth of the children's route and move it one more step down. I need to change my code now to say this.route. parent.parent.parent .params
2) Or say that it is the 10th (generation ?, sub-child ?, great-great-great-great-grandmother?). Should I then say: this.route. parent.parent.parent.parent.parent.parent.parent.parent.parent .params
--- Edit: added routing configuration files ---
app.routing.ts
const routes: Routes = [ {path: 'app', loadChildren: './views/private/private.module#PrivateModule'} ];
private.routing.ts
const routes: Routes = [{ path: '', component: PrivateComponent, children: [ {path: 'project', loadChildren: './project/project.module#ProjectModule'}, {path: '', redirectTo: 'project', pathMatch: 'full'} ]
project.routing.ts
const routes: Routes = [{ path: ':projectId', component: ProjectComponent, children: [ {path: 'views', loadChildren: './views/views.module#ViewsModule'}, {path: '', redirectTo: 'views', pathMatch: 'full'} ]