Angular2 子模块的 forChild() 路由覆盖根路由

标签 angular angular2-routing

当使用 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/

相关文章:

javascript - Angular 2 如何使基于父容器的 div 出现

angular - 如何在 Angular 5 中的 Angular Material Snackbar 中添加图标

angular - 即使必填字段为空白,在表单内单击时也会以 Angular 提交

google-maps - angular2-google-maps 自动完成功能不起作用

angular - 无法匹配任何路线

Angular2 路由器 : how to correctly load children modules with their own routing rules

Angular 垫按钮,如何禁用焦点覆盖

javascript - Angular 2/4 动态加载脚本

typescript - Angular 2 中的 RouteData 可以将变量从父组件传递给路由组件吗?

Angular 4 : Passing object to Routes without updating Query Params