Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 project. For each of these projects, I have its details spread accross different sections / routes:

  • project/:id/overview
  • project/:id/documents
  • project/:id/logs
  • etc

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

like image 446
yorch Avatar asked Sep 28 '16 09:09

yorch


2 Answers

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

ngOnInit() {
    this.route.parent.data.subscribe(data => {
        this.project = data.project;
    });
}
like image 96
Oleg Avatar answered Oct 17 '22 02:10

Oleg


Depend on how far is your resolve object by the component hierarchy you can reach it by the parentproperty.

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!

like image 24
Mikki Kobvel Avatar answered Oct 17 '22 03:10

Mikki Kobvel