首页 > 解决方案 > 具有延迟加载问题的角嵌套路由

问题描述

我有一个应用程序,我只需要在启动时就可以使用登录功能,并且所有剩余的代码都应该在用户身份验证后延迟加载。

我创建了一个带有core-routing.module和 core.component 的core.module处理这个问题,但是子组件(例如 DashboardComponent)正在 app.component.html 上的 router-outlet 元素中呈现,而不是在core.component.html 等标题没有被显示。

我已经搜索了很多,但找不到如何让它工作。

应用程序路由.module.ts

const routes: Routes = [
  { path: '', redirectTo: 'signin', pathMatch: 'full' },
  { path: 'signin', component: SigninComponent },
  { path: 'app', loadChildren: './core/core.module#CoreModule', canLoad: [AuthGuard] },
  { path: '**', redirectTo: 'signin' }
];

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

app.component.html

<router-outlet></router-outlet>

核心路由.module.ts

const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule', canLoad: [AuthGuard] },
  { path: '**', redirectTo: 'dashboard' }
];

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

core.component.html

<div id="header">
  <app-header></app-header>
</div>
<main id="content">
  <router-outlet></router-outlet>
</main>

仪表板-routing.module.ts

const dashboardRoutes: Routes = [
  { path: '',  component: DashboardComponent, pathMatch: 'full' }
];

@NgModule({
imports: [
  CommonModule,
  MaterialModule,
  SharedModule,
  RouterModule.forChild(dashboardRoutes)
],

标签: angularangular-router

解决方案


在尝试了许多不同的方式之后,对我有用的是将 core-routing.module.ts 更改为具有单个路由,并将延迟加载的模块作为子模块包含在其中:

const routes: Routes = [
  {
    path: '',
    component: CoreComponent,
    children: [
      { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
      { path: 'dashboard', loadChildren: '../dashboard/dashboard.module#DashboardModule', canLoad: [AuthGuard] },
      { path: 'customers', loadChildren: '../customers/customers.module#CustomersModule', canLoad: [AuthGuard] },
      { path: 'history', loadChildren: '../history/history.module#HistoryModule', canLoad: [AuthGuard] },
      { path: 'processing', loadChildren: '../processing/processing.module#ProcessingModule', canLoad: [AuthGuard] },
      { path: '**', redirectTo: 'dashboard' }
    ]
  }
];

希望这可以帮助尝试实现相同功能的人。


推荐阅读