官方文档:
https://angular.io/guide/lazy-loading-ngmodules
关键词:路由、懒加载、特性模块
在angular5以上版本官方给的方法是新建两个带路由的模块,再在模块中添加组件,这样根路由包括这两个模块,各自模块又能找到路由,代码如下:
ng new customer --routing
ng generate module customers –routing
ng generate component customers/customer-list
ng generate module orders –routing
ng generate component orders/order-list
根页面HTML代码:
<button routerLink="/customers">Customers</button>
<button routerLink="/orders">Orders</button>
<button routerLink="">Home</button>
<router-outlet></router-outlet>
找到各自模块需要在根路由中设置,注意loadChildren:
src/app/app-routing.module.ts
const routes: Routes = [
{
path: 'customers',
loadChildren: './customers/customers.module#CustomersModule'
},
{
path: 'orders',
loadChildren: './orders/orders.module#OrdersModule'
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];
各自特性模块基本在创建组件时会import组件名称,基本不用管,只需在该模块的路由中添加子组件的路由:
src/app/customers/customers-routing.module.ts:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CustomerListComponent } from './customer-list/customer-list.component';
const routes: Routes = [
{
path: '',
component: CustomerListComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class CustomersRoutingModule { }
注意:path后是空格