I have been trying to alter lazy loading routes in Angular at runtime.
I created a GitHub issue but they asked me to create a question here.
const routes: Routes = [
{ path: '', component: SetupComponent },
{ path: 'usermanagement', loadChildren: () => import('./usermanagement/usermanagement.module').then(m => m.UsermanagementModule) },
{ path: 'organization', loadChildren: () => import('./organization/organization.module').then(m => m.OrganizationModule) },
];
User management routes:
const routes: Routes = [
{ path: 'users', loadChildren: () => import('./users/users.module').then(m => m.UsersModule) },
{ path: 'roles', loadChildren: () => import('./roles/roles.module').then(m => m.RolesModule) },
];
User routes:
const routes: Routes = [
{ path: '', component: UsersComponent },
{ path: 'new', component: UserNewComponent },
{ path: 'edit/:id', component: UserEditComponent }
];
At the application start, I would like to inject a route /usermanagement/users/xxxxx
in the Users Module or change the component associated with the /users/new
route.
{ path: 'xxxxx', component: DynamicComponent }
I did try the following, but it is always loading original routes:
if (parentRoute.loadChildren) {
await(<any>this.router).configLoader.load(this.injector, parentRoute).subscribe({
next: (moduleConf: any) => {
let routestoUpdate: Routes = moduleConf.routes;
if (`${routeToAdd}` === "") {
routestoUpdate = this.removeExistingRoutes(routestoUpdate, "");
routestoUpdate = this.removeExistingRoutes(routestoUpdate, "new");
routestoUpdate = this.removeExistingRoutes(routestoUpdate, "edit/:id");
} else {
routestoUpdate = this.removeExistingRoutes(routestoUpdate, `${routeToAdd}`);
routestoUpdate = this.removeExistingRoutes(routestoUpdate, `${routeToAdd}/new`);
routestoUpdate = this.removeExistingRoutes(routestoUpdate, `${routeToAdd}/edit/:id`);
}
routestoUpdate.push(
{
path: `${routeToAdd}`,
component: BeholderHomeComponent,
data: { breadcrumb: customRoute.display_name, link: false, page_id: customRoute.page_id }
},
{
path: `${routeToAdd}` === "" ? "new" : `${routeToAdd}/new`,
component: BeholderNewComponent,
data: { breadcrumb: 'BUTTON.NEW', link: false, page_id: customRoute.page_id }
},
{
path: `${routeToAdd}` === "" ? "edit/:id" : `${routeToAdd}/edit/:id`,
component: BeholderEditComponent,
data: { breadcrumb: 'BUTTON.EDIT', link: false, page_id: customRoute.page_id }
}
);
** WHAT IS RIGHT WAY TO UPDATE USERS ROUTES**
moduleConf.routes = [...routestoUpdate];
// moduleConf.routes = routestoUpdate;
// moduleConf.module.injector.get(Router).resetConfig(routestoUpdate);
setTimeout(async () => {
await this.compiler.compileModuleAsync(moduleConf.module.injector.instance);
this.router.config.unshift(...routestoUpdate);
}, 500);
}
});
}
How can I dynamically change routes at runtime?