首页 > 解决方案 > 嵌套路由器:父路由有效,子路由无

问题描述

在 Angular 8 中,我创建了一个带有主路由的应用程序,在主路由内部有一个带有另一个子路由的组件。

我有几个问题:当我插入现有路径时,url 似乎是正确的,但未显示组件,而如果我插入错误的 url,404 重定向就会生效。

父路由有效,而子路由无效。

我发现的另一个问题是在链接中,我无法在链接中插入“父亲/儿子姓名”,只出现儿子姓名。在我看来,手动输入父亲的名字:“父亲/父亲/儿子”。

我附上下面的代码

App.Routing.Module.ts

    const routes: Routes = [
  {path: 'main', component: MainComponent, loadChildren: () => import('./main/main.module').then(m=>m.MainModule), canActivate: [AuthGuard]},

  {path: '', component: MainComponent, canActivate: [AuthGuard]},
  {path: 'login', component: LoginComponent},
  {path: 'register', component: RegisterComponent},

  //THIS REDIRECT TO HOME
  {path: '**', redirectTo: '/login'}
];

@NgModule({
  imports: [RouterModule.forRoot(routes,{enableTracing: true})],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Main.Routing.Module.TS

const routes: Routes = [{
  path: '', component: ColumnChartComponent,  children:[
    {path: 'pie', component: PieChartComponent},
    {path: 'dashboard', component: LayoutDashboardComponent},
    {path: '**', redirectTo: '', pathMatch: 'full'}
  ]
}];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MainRoutingModule { }

预先感谢您的帮助

标签: angularangular-routing

解决方案


我很确定你不能有一个延迟加载的路由(你的 loadChildren()),除了那个路由字符串中的一个组件。所以请改变

{path: 'main', component: MainComponent, loadChildren: () => import('./main/main.module').then(m=>m.MainModule), canActivate: [AuthGuard]}

至:

{path: 'main', loadChildren: () => import('./main/main.module').then(m=>m.MainModule), canActivate: [AuthGuard]}

推荐阅读