[英]Angular : Lazy load multiple Modules with the same route
我有一个应用程序,我想在同一时刻使用相同的路由路径延迟加载两个模块。
我的路由模块如下所示:
{
path: 'mypath',
loadChildren: () => HomeModule,
canLoad: [HomeGuard]
},
{
path: 'mypath',
loadChildren: () => AdvisorModule,
canLoad: [AdvisorGuard]
},
但这导致只加载第一个
我无论如何都找不到这样做,例如:
{
path: 'mypath',
loadChildren: () => HomeModule, advisor module // ??
canLoad: [// ??]
},
我也不想在另一个中导入其中一个,就像这样,只有一个模块会被延迟加载,而另一个会自动加载
怎么可能呢??
您需要将路线重新排列一级,还需要为要加载的额外组件添加辅助路线。
这适用于 Angular 9(也可能适用于 8)
{
path: 'home',
component: HostingComponentWithOutlets,
children: [
{
path: 'featureOne',
loadChildren: () => import('xxxxx').then(m => m.FeatureOneModule),
canLoad: [featureOneGuard]
},
{
path: 'featureTwo',
outlet: 'outletAux1',
loadChildren: () => import('yyyyy').then(m => m.FeatureTwoModule),
canLoad: [featureTwoGuard]
},
// you can even load more components to different outlets from the same module
// and update redirectTo and routerLink accordingly
//{
// path: 'featureThree',
// outlet: 'outletAux2',
// loadChildren: () => import('yyyyy').then(m => m.featureTwoModule),
// canLoad: [featureTwoGuard]
//},
{
path: '',
redirectTo:
'/absolute/path/to/home(featureOne/path-to-featureOne-component//outletAux1:featureTwo/path-to-featureTwo-component)',
pathMatch: 'full'
}
]
},
{ path: '', redirectTo: 'home', pathMatch: 'full' }
点击“home”路线将延迟加载所有必需的模块。
在您需要链接到“featureOne”的HostingComponentWithOutlets
html 模板中:
<a [routerLink]="featureOne/path-to-featureOne-component"
如果您想使用模板中的辅助路线直接进入完整路线:
<a [routerLink]="['.', { outlets: { 'primary': ['featureOne', 'path-to-featureOne-component'], 'outletAux1': ['featureTwo', 'path-to-featureTwo-component'] } }]"
FeatureOneModule
应定义“path-to-featureOne-component”,而FeatureTwoModule
应在其等效路由定义中定义“path-to-featureTwo-component”。
你可以像这样返工:
const routes: Routes = [
{
path: 'mypath/home',
loadChildren: () => HomeModule,
canLoad: [HomeGuard]
},
{
path: 'mypath/advisor',
loadChildren: () => AdvisorModule,
canLoad: [AdvisorGuard]
},
]
换句话说,将模块的路径路径移到父模块之外,在这种情况下,我假设它们是“顾问”和“家”
然后使用重定向解决方案和/或像这样的路径在模块路由中开始:
家庭模块路由:
const routes: Routes = [
{
path: '', // <-- in your current solution probably 'home'
component: HomeParentComponent,
children: [
{ path: '', redirectTo: 'childOne', pathMatch: 'full' },
{ path: 'childOne', component: HomeChildComponentOne },
],
},
];
顾问模块路由:
const routes: Routes = [
{
path: '', // <-- in your current solution probably 'advisor'
component: AdvisorParentComponent,
children: [
{ path: '', redirectTo: 'childOne', pathMatch: 'full' },
{ path: 'childOne', component: AdvisorChildComponentOne },
],
},
];
这很好用,您应该能够导航到:
'/mypath/home'
并以HomeParentComponent
的路由器出口结束在您的HomeChildComponent
。
'/mypath/advisor'
并最终在您的AdvisorParentComponent
使用AdvisorChildComponent
路由器出口之一。
如果您不希望路由器插座内有子组件,那就更简单了,您可以删除子路由并重定向。
注意:如果此解决方案不能解决您的问题,请分享有关您的模块路由的更多详细信息,以便我可以更好地了解您所需的路由配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.