Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Sibling child routes sharing same resolver

I am trying to figure out if there is a more optimize way in sharing the same resolver between two sibling children routes. Below is an example of how the routes are related with the resolvers.

import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
export const routes = [{
        path: '',
        component: parentComponent,
        canActivate: [AuthGuard],
        resolve: {
            someData: someDataResolver
        },
        children: [
            { path: '', redirectTo: '0', pathMatch: 'full' },
            { path: '0', 
                component: someComponent1,
                resolve: {
                    someData1: someData1Resolver,
                    someData2: someData2Resolver,
                }
            },
            { path: '2', 
                component: someComponent2,
                resolve: {
                    someData2: someData2Resolver
                }
            }
            ... a bunch more children routes/components with resolvers

        ]
    }]

Right now, I am repeating the resolvers calls for each children routes, which I believe isn't optimal. Do anyone know if there is a better way to share the data from a shared sibling child resolver? I thought about setting the data from a duplicate resolver to a shared service, which then the other child sibling route would access the data from the service (rather than making another api call in the resolver). Are there any other more optimal solutions?

like image 798
PBandJen Avatar asked Feb 06 '23 19:02

PBandJen


1 Answers

You can add an additional level with a componentless parent route and move up the resolver to this level:

import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
export const routes = [{
        path: '',
        component: parentComponent,
        canActivate: [AuthGuard],
        resolve: {
            someData: someDataResolver
        },
        children: [
            { path: '', 
                resolve: {
                    someData2: someData2Resolver
                },

            children: [
                { path: '', redirectTo: '0', pathMatch: 'full' },
                { path: '0', 
                    component: someComponent1,
                    resolve: {
                        someData1: someData1Resolver,
                    }
                },
                { path: '2', 
                    component: someComponent2,
                }
                ... a bunch more children routes/components with resolvers
            ]
        ]
    }]
like image 158
Günter Zöchbauer Avatar answered Feb 24 '23 05:02

Günter Zöchbauer