嗨,我在我的示例中使用延迟加载。
export const appRoutes: Routes = [
{ path: 'comp1', loadChildren: 'app/components/comp1/comp1.module#comp1Module' },
{ path: 'comp2', loadChildren: 'app/components/comp2/comp2.module#comp2Module' },
. . .
]
comp1Module 具有以下子路线 Routes
export const comp1Routes: Routes = [
{ path: 'comp1/default', component: DefaultComponent },
];
在路由时我需要从模块中获取所有路由。
例如:我想从模块中获取所有路由comp1
您可以通过注入 Router 并拉取配置来使用 router.config。
constructor(private router: Router){
console.log(this.router.config);
}
我使用这种方法:
将延迟加载的模块路由定义为根组件的子组件:
const routes: Routes = [
{ path: '', component: LazyLoadedRootComponent,
children: [
{ path: 'child1', component: Child1Component },
{ path: 'child2', component: Child2Component },
]
}
];
@NgModule({
declarations: [LazyLoadedRootComponent, Child1Component, Child2Component],
imports: [
CommonModule,
RouterModule.forChild(routes)
]
})
export class LazyLoadedModule { }
然后从您的根模块组件中,您可以像这样获得它的子路由:
export class LazyLoadedRootComponent implements OnInit {
constructor(private route: ActivatedRoute) {
}
ngOnInit(): void {
console.log(this.route.routeConfig.children);
}
}
想象一下你的 app-routing.module.ts 看起来像这样:
const routes: Routes = [
{
path: 'first-module',
loadChildren: () => import('./modules/first-module/first.module').then(m => m.FirstModule)
},
{
path: 'second-module',
loadChildren: () => import('./modules/second-module/second.module').then(m => m.SecondModule)
},
你的 first-routing.module.ts 看起来像这样
const routes: Routes = [
{
path: 'first-page',
component: FirstPageComponent,
data: {
someData: 'abc'
}
},
{
path: 'second-page',
component: SecondPageComponent,
data: {
extendedData: 'XYZ'
}
},
您可以像这样获取特定模块路由的路由和配置。 如果没有该任播,您将收到错误消息“属性‘_loadedRoutes’在类型‘Route’上不存在。”
private getModuleRoutes(): Route[] {
return (this.router.config.find(routeConfig=>
routeConfig.path === 'first-module'
) as any)._loadedRoutes;
}