当使用 loadChildren() 调用导入子路由时,我遇到了覆盖根路由的问题。
应用路由声明为:
const routes: Routes = [
{ path: '', redirectTo: 'own', pathMatch: 'full' },
{ path: 'own', component: OwnComponent },
{ path: 'nested', loadChildren: () => NestedModule},
];
export const routing = RouterModule.forRoot(routes);
嵌套子模块的路由:
const routes: Routes = [
{ path: 'page1', component: NestedPage1Component },
{ path: 'page2', component: NestedPage2Component },
{ path: '', redirectTo: 'page1', pathMatch: 'full' },
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class Module1RoutingModule {}
我可以获取/own、/nested/page1、/nested/page2,但是当我尝试获取 root/时 - 我正在重定向到/page1。为什么会发生这种情况,因为它是在带有 RouterModule.forChild 的子模块中声明的,它如何重定向到不/own ?
我为重现创建了简单的 plunk - https://plnkr.co/edit/8FE7C5JyiqjRZZvCCxXB?p=preview
有人经历过这种行为吗?
最佳答案
这是您的 fork 和修改后的 plunker:https://plnkr.co/edit/XilkY55WXle2hFF0Pelx?p=preview
不要导入延迟加载模块并像这样更改根路由:
//import { Module1Module } from "./module1/module1.module"; // do NOT import it !
export const routes: Routes = [
{ path: '', redirectTo: 'own', pathMatch: 'full' },
{ path: 'own', component: OwnComponent },
{ path: 'module1', loadChildren: 'src/module1/module1.module#Module1Module' },
];
和嵌套路由:
const routes: Routes = [
//{ path: 'page1', component: Module1Page1Component },
//{ path: 'page2', component: Module1Page2Component },
//{ path: '', redirectTo: 'page1', pathMatch: 'full' },
// do the routes like this..
{
path: '',
component: Module1Component,
children: [
{ path: '', redirectTo: 'page1', pathMatch: 'full' },
{ path: 'page1', component: Module1Page1Component },
{ path: 'page2', component: Module1Page2Component }
]
},
];
关于Angular2 子模块的 forChild() 路由覆盖根路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40816415/