yorch yorch - 1 year ago 253
AngularJS Question

Angular 2 - Use same resolver for parent and child routes

I have an Angular 2.0 (stable version) app where one of the entities is

. For each of these
, I have its details spread accross different sections / routes:

  • project/:id/overview

  • project/:id/documents

  • project/:id/logs

  • etc

The API for
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 },

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
code in the child components, thinking that maybe the Angular Router would pass the route data as well, but no success.

Any ideas please?


Answer Source

You can use 'parent' property of 'route' to get data from parent resolvers.

ngOnInit() {
    this.route.parent.data.subscribe(data => {
        this.project = data.project;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download