I am trying to modify routes in a lazy-loaded feature module but no success. I tried several approaches including router.reset(newRoutes)
but none seem to work. (Angular 9)
export class FeatureModule {
static forRoot(routes?: Routes) {
return {
ngModule: FeatureModule,
providers: [
RouterModule.forChild(routes).providers // option 1
// provideRoutes(routes), // option 2
// { provide: ROUTES, useValue: routes }, // option 3
]
}.ngModule
}
}
FeatureModule
is lazy loaded into the main app:
loadChildren: () => import('./feature/feature.module').then((m) => m.FeatureModule.forRoot(customRoutes)
None of the options work. Angular does not detect those dynamically provided routes
If I provide static default routes in the imports
then it works but then I am not able to modify the routes
@NgModule({
imports: [RouterModule.forChild(defaultRoutes)]
})
export class FeatureModule { }
I wonder if this has something to do with Angular itself or I am doing something wrong
That will not work, because imports
and providers
are two different things and the RouterModule is a Module so it should be placed in the imports
section.
Using dynamic routes in a lazy-module it's a little tricky, i dont know if there is another way, but you could try the following:
Use and export a variable in the FeatureModule
and fill the routes on the lazy-load.
export const FeatureModuleRoutes = [];
@NgModule({
imports: [RouterModule.forChild(FeatureModuleRoutes)]
})
export class FeatureModule { }
Lets create an InjectionToken and store the routes in there.
//Create the injection token
const ROUTES_STORE = new InjectionToken("Loading lazy routes");
//In your AppModule provide the routes that you need.
{
provide: ROUTES_STORE,
useValue: [{featureRoutes: [{path: "", component: FeatureComponent}]}]
},
To inject the token you need an injector, the AppModule it is called before the lazy-load, so you could provide an static injector and use it later.
export class AppModule {
static mInjector: Injector;
//Inject the Injector so we can access it before de Lazy Module
constructor(injector: Injector) {
AppModule.mInjector = injector;
}
}
Now you have an injector and the routes, it is time to fill your FeatureModuleRoutes. The m
it is the file so you can access to your variable before is loaded.
loadChildren: () =>
import("./feature/feature.module").then(m => {
const routeStore = AppModule.mInjector.get(ROUTES_STORE);
routeStore.featureRoutes
.forEach(route => (m.FeatureModuleRoutes as Array<any>).push(route));
return m.FeatureModule;
})
And that is it, let me know if it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.