延迟加载模块的路由配置结构不同,因为延迟加载模块有自己单独的路由配置。就我而言,我从数据库中获取了路由,并且需要在用户成功登录时将它们应用到 router.config。
核心模块在路径“core”上的应用程序模块中延迟加载。
应用程序路由.modules.ts
const routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'core', loadChildren: () => import('@modules/pu-core/pu-core.module').then(m => m.PuCoreModule) }
];
核心模块
const routes: Routes = [
{ path: 'layout', component: LayoutComponent, childre:[] },
];
登录成功后,auth 服务有一个可观察的
apiRoutes$
,其中包含需要应用于 layout
路径子级的路由。
使用
this.router.config
动态添加子项不起作用,因为配置不同。
以下实现不起作用:
constructor(public router: Router, private activatedRoute: ActivatedRoute, @SkipSelf() private auth: AuthService) {
this.auth.routes$.subscribe(
(routesData: any) => {
this.router.config[2].children = routesData;
}
)
}
constructor(private puCoreRoutingService: PuCoreRoutingService) {}
onLoginSuccess(): void {
this.auth.routes$.subscribe((routesData: Routes) => {
this.puCoreRoutingService.updateLayoutChildrenRoutes(routesData);
});
}
import { Injectable } from '@angular/core';
import { Router, Routes } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class PuCoreRoutingService {
constructor(private router: Router) {}
public updateLayoutChildrenRoutes(routes: Routes): void {
const config = this.router.config;
const layoutRoute = config.find(r => r.path === 'layout');
if (layoutRoute) {
layoutRoute.children = routes;
this.router.resetConfig(config);
}
}
}