问题
USER 1
{
path: 'dashboard',
component: DashboardComponent,
children: [
{ path: 'users', component: UsersComponent },
],
canActivate: [AuthGuard],
{ path: '**', redirectTo: 'dashboard', pathMatch: 'full' }
}
USER 2
{
path: 'dashboard',
component: DashboardComponent,
children: [
{ path: 'reception', component: ReceptionComponent },
{ path: 'restaurants', component: RestaurantsComponent },
...
],
canActivate: [AuthGuard],
{ path: '**', redirectTo: 'dashboard', pathMatch: 'full' }
}
How to implement this logic within application RouterModule? If I load it from Database
This is an example I'm trying to implement but it doesn't work
export function routesFactory(routesService: RoutesService, injector: Injector) {
return () => {
const router = injector.get<Router>(Router);
routesService.getRoutesForLayout().subscribe((routes: RouteDto[]) => {
routes.map((route: RouteDto) => {
let component = routingComponents.get(route.component);
if (!component) {
component = null;
}
let addedRoute: Route;
if (route.children.length > 0) {
addedRoute = {
path: route.path,
component: component,
canActivate: [AuthGuard]
};
addedRoute.children = route.children.map(childRoute => {
const childRoutes: Route = {
path: childRoute.path,
component: routingComponents.get(childRoute.component) || null,
redirectTo: childRoute.redirectTo || null,
pathMatch: childRoute.pathMatch || null
};
return childRoutes;
})
}
router.config.push(addedRoute);
});
});
};
}
usage:
@NgModule({
imports: [
BrowserModule,
SharedClientAuthModule,
SharedLayoutModule,
SharedUtilitiesModule,
RouterModule.forRoot(appRoutes),
environment.production ? [] : AkitaNgDevtools.forRoot()
],
providers: [{
provide: APP_INITIALIZER,
useFactory: initializer,
deps: [ConfigurationService],
multi: true
}, {
provide: APP_INITIALIZER,
useFactory: routesFactory,
deps: [RoutesService, Injector]
}],
declarations: [DashboardComponent, DevicesComponent, UsersComponent, ButtonViewComponent, CheckInComponent, CheckOutComponent],
bootstrap: [DashboardComponent]
})
export class AppModule {
}
The decorator:
/***
* Routing components storage
* @type {Map<string, Function>}
*/
export let routingComponents = new Map<string, Function>();
/***
* Decorator function
* @returns {function(any): *}
* @constructor
*/
export function RoutingComponent(name?: string) {
return function (target:any) {
routingComponents.set(name || target.name, target);
return target;
}
}
RouteDTo
export class RouteDto {
path: string;
component?: string;
children?: RouteDto[];
pathMatch?: string;
redirectTo?: string;
}
来源:https://stackoverflow.com/questions/60742914/dynamic-routes-with-children-and-components-from-database