Angular 5 懒加载

详细步骤+源代码请点击这里

Before

// app.module.ts
@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    SystemModule,
    AppRoutingModule
    ...
  ],
  providers: [
   ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}
// app-routing.module.ts
const appRoutes: Routes = [
  ...
  {
    path: 'zygl/system',
    canActivate: [AuthGuardService],
    component: SystemComponent
  }
  ...
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes, {useHash: true})
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {
}
//system.module.ts
@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [SystemComponent],
  exports: [SystemComponent],
  providers: []
})
export class SystemModule {
}

After

// app-routing.module.ts
const appRoutes: Routes = [
  ...
  {
    path: '',
    canActivate: [AuthGuardService],
    loadChildren: 'app/component/system/system.module#SystemModule'
  }
  ...
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes, {useHash: true})
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {
}
//system.module.ts
@NgModule({
  imports: [
    CommonModule,
    SystemRoutingModule,
  ],
  declarations: [SystemComponent],
  exports: [SystemComponent],
  providers: []
})
export class SystemModule {
}
// system-routing.module.ts
const systemRoutes: Routes = [
  {
    path: 'zygl/system',
    component: SystemComponent
  }

];

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

步骤
1.将上级路由中想要懒加载的路径改为空,即''
2.将上级路由中想要懒加载的component: xxComponent替换为loadChildren: 'app/component/xx.module#xxModule'
3.在xxModule 的路由中写原上级路由的参数如

const systemRoutes: Routes = [
  {
    path: 'zygl/system',
    component: SystemComponent
  }

];

注意
子路由是

 RouterModule.forChild(systemRoutes)

此外imports的时候 子路由要在上级路由的上面
如果需要在懒加载路由上加children

const systemRoutes: Routes = [
  {
    path: 'zygl/system',
    component: SystemComponent,
    children: [
      {
        path: '',
        redirectTo: 'department',
        pathMatch: 'full'
      },
      {
        path: 'department',
        component: DepartmentComponent
      },
      {
        path: '**',
        component: NoContentComponent
      }
    ]
  }

];

component: SystemComponent,如果没写 会发生system.component.html内容失效的情况

你可能感兴趣的:(Angular 5 懒加载)