Angular 延迟加载和子路由设置

Angular with lazy loading and child routes setup

我正在尝试设置 Angular (8) 延迟加载,但我不知道如何让它工作。

我有 3 个模块,每个模块都有不同的子路径 :

任何人都可以提供有关如何正确实现此功能的工作示例吗?

谢谢

编辑 = 这是我的主模块的路由代码:

{ path: 'home', component: HomeComponent, canActivate: [AuthGuardService], children: [ { path: '', component: DashboardComponent, canActivate: [AuthGuardService] }, { path: 'upgrade', component: StripeFormComponent, canActivate: [AuthGuardService] } ] }, ];

我尝试在应用程序中添加延迟加载-routing.module.ts。我重新加载了我的应用程序,看起来代码少了一点,我的模块看起来是延迟加载的,但是当我尝试访问该页面时,我得到了一个没有任何解释的空白页面。所以我迷路了。

要在 Angular 8 中延迟加载设置路由,您必须为要访问的组件定义一个模块,其中必须定义一个 routing.module:

 @NgModule({
      declarations: [
        DetailComponent,
      ],
      imports: [
        DetailRoutingModule,
        ChartsModule,
        CommonModule
      ]
    })

export class DetailModule { }

而 YorComponentDetailRoutingModule 是

const routes: Routes = [{
  path: '',
  component: DetailComponent,

}];

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


export class DetailRoutingModule { }

In app.routing module you can write:

const routes: Routes = [{
  path: '',
  component: PagesComponent,
  children: [
    {
      path: 'home',
      component: HomeComponent
    },{
      path: 'home/detail',
      loadChildren: () => import('./detail/detail.module')
      .then(m => m.DetailModule),
    } ...

一种方法是您可以为每个模块中的组件决定一些通用路径名(例如模块 1 的 'home')。那么

  `const routes: Routes = [
   { path: 'home', loadChildren: () => import('./core/core.module').then(m => m.CoreModule) }
   { path: 'module2', loadChildren: () => import('<path to module>').then(m => m.module2) }
   { path: 'module3', loadChildren: () => import('<path to module>').then(m => m.module3) }
 ];`

然后在每个模块中,您可以同样为每个组件定义路径

`const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'asset/:id', component: AssetComponent },
  { path: 'sub/:id', component: SubCategoryComponent },
];`

这样,只有包含与路径匹配的组件的模块才会被加载。