路由模块懒加载

通过 Angular 自定义模块可以实现路由的懒加载

1.创建模块和模块下的组件,并配置模块路由

//创建模块:
ng g module module/user --routing  //--routing  创建模块的同时创建模块路由
ng g module module/article --routing
ng g module module/product --routing
//创建组件:
ng g component module/userng g component module/user/components/profile
ng g component module/user/components/order
ng g component module/article
ng g component module/article/components/articlelist
ng g component module/article/components/info
ng g component module/product
ng g component module/product/components/plist
ng g component module/product/components/pinfo
1
2
3
4
5
6
7
8
9
10
11
12
13
//user-routing.module.ts
import { UserComponent } from './user.component';
import { ProfileComponent } from './components/profile/profile.component';
import { AddressComponent } from './components/address/address.component';
const routes: Routes = [
  {
    path: '', component: UserComponent,
    children: [
      { path: 'profile', component: ProfileComponent },
      {path: '**',component:ProfileComponent}
    ]
  },
  { path: 'address', component: AddressComponent }
];
1
2
3
4
5
6
7
8
9
10
11
12
13
14

2.配置模块懒加载

//app-routing.module.ts
const routes: Routes = [
  {
    path:'user',loadChildren:'./module/user/user.module#UserModule'
  },{
    path:'product',loadChildren:'./module/product/product.module#ProductModule'
  },{
    path:'article',loadChildren:'./module/article/article.module#ArticleModule'
  },
  {
    path:'**',redirectTo:'user'
  }
];
1
2
3
4
5
6
7
8
9
10
11
12
13

3.根组件及user组件中跳转路由

<!-- app.component.html -->
<header>
    <a [routerLink]="[ '/user'  ]">用户模块</a>
    <a [routerLink]="[ '/product'  ]">商品模块</a>
    <a [routerLink]="[ '/article' ]">文章模块</a>
</header>
<router-outlet></router-outlet>
1
2
3
4
5
6
7
<!-- user.component.html -->
<p>user works!</p>
<a [routerLink]="[ './profile' ]">个人中心</a>
<a [routerLink]="[ './address' ]">个人地址</a>
<router-outlet></router-outlet>
1
2
3
4
5