I have an Angular 2.0 (stable version) app where one of the entities is project
. For each of these projects
, I have its details spread accross different sections / routes:
project/:id/overview
project/:id/documents
project/:id/logs
The API for project
returns most of the data in a single call, so I need to call it once, and make it available for the different child routes.
My routes looks like:
export const routing: ModuleWithProviders = RouterModule.forChild([
{ path: 'projects', component: ProjectsComponent },
{ path: 'project/new', component: NewProjectComponent },
{
path: 'project/:id',
component: ProjectDetailComponent,
resolve: {
project: ProjectDetailResolve
},
children: [
{ path: '', redirectTo: 'overview', pathMatch: 'full' },
{ path: 'overview', component: ProjectOverviewComponent },
{ path: 'documents', component: DocumentsComponent },
{ path: 'logs', component: LogsComponent },
]
}
]);
ProjectDetailComponent
currently gets the project data successfully, with the Resolver (no problems there) by using:
ngOnInit() {
this.route.data.forEach((data: { project: any }) => {
this.project = data.project;
});
}
But I need to pass that same project down to the child routes as it doesn't make sense to trigger another API call for each of those routes.
I've tried using the same ngOnInit
code in the child components, thinking that maybe the Angular Router would pass the route data as well, but no success.
Any ideas please?
Thanks
You can use 'parent' property of 'route' to get data from parent resolvers.
ngOnInit() {
this.route.parent.data.subscribe(data => {
this.project = data.project;
});
}
Depend on how far is your resolve object by the component hierarchy you can reach it by the parent
property.
Examples:
ngOnInit() {
this.route.parent.data.subscribe(data => this.project = data.project);
}
Or without subscription
ngOnInit() {
this.project = this.route.snapshot.parent.data['project'];
}
P.S.
Keep in mind that in case you component is deeper than one level, you can chain parent
property unlimited amount of times. Like this.route.snapshot.parent.parent.data['project']
. Cheers!
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