模块配置路由

创建带路由的模块

使用 --routing 参数创建带有路由的模块user:

  1. ng g module module/user --routing

在路由中配置懒加载模块

在根模块的路由中以懒加载方式配置模块:

  1. import { NgModule } from '@angular/core';
  2. import { Routes, RouterModule } from '@angular/router';
  3. // 在app.module.ts中加入相关模块后,路由中不再在前面直接引入,配置成懒加载模式
  4. const routes: Routes = [
  5. // 旧版Angular配置方式:loadChildren: '模块#模块的类'
  6. // {path: 'user', loadChildren: './module/user/user.module#UserModule'},
  7. // 新版Angular的配置方式:loadChildren: () => import('模块').then(m => m.模块的类)
  8. {path: 'user', loadChildren: () => import('./module/user/user.module').then(m => m.UserModule)},
  9. {path: 'product', loadChildren: () => import('./module/product/product.module').then(m => m.ProductModule)},
  10. {path: 'artical', loadChildren: () => import('./module/artical/artical.module').then(m => m.ArticalModule)},
  11. {path: '**', redirectTo: 'product'}
  12. ];
  13. @NgModule({
  14. imports: [RouterModule.forRoot(routes)],
  15. exports: [RouterModule]
  16. })
  17. export class AppRoutingModule { }

配置自定义模块的组件路由

  1. 在user-routing.module.ts中配置自定义模块的组件 ```typescript import { NgModule } from ‘@angular/core’; import { Routes, RouterModule } from ‘@angular/router’;

// 加入相关组件 import { UserComponent } from ‘./user.component’; import { ProfileComponent } from ‘./components/profile/profile.component’; import { AddressComponent } from ‘./components/address/address.component’;

// 在app.module.ts中配置了user模块的路由为’user’,user模块内的路由访问时前面要加’/user’ const routes: Routes = [ {path: ‘’, component: UserComponent}, // 访问http://localhost:4200/user {path: ‘profile’, component: ProfileComponent}, // 访问http://localhost:4200/user/profile {path: ‘address’, component: AddressComponent} // 访问http://localhost:4200/user/address ];

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

  1. 2.
  2. product.routing.ts中以嵌套路由方式配置组件
  3. ```typescript
  4. import { NgModule } from '@angular/core';
  5. import { Routes, RouterModule } from '@angular/router';
  6. import { ProductComponent } from './product.component';
  7. import { PlistComponent } from './components/plist/plist.component';
  8. import { CartComponent } from './components/cart/cart.component';
  9. import { PcontentComponent } from './components/pcontent/pcontent.component';
  10. // 在app.module.ts中配置了product模块的路由为'product',product模块内的路由访问时前面要加'/product'
  11. const routes: Routes = [
  12. {path: '', component: ProductComponent, // 访问http://localhost:4200/product
  13. // 配置ProductComponent组件的嵌套子路由,可在ProductComponent组件的html中使用<router-outlet>标签展示
  14. children: [
  15. {path: 'plist', component: PlistComponent},
  16. {path: 'cart', component: CartComponent},
  17. {path: 'pcontent', component: PcontentComponent}
  18. ]
  19. }
  20. ];
  21. @NgModule({
  22. imports: [RouterModule.forChild(routes)],
  23. exports: [RouterModule]
  24. })
  25. export class ProductRoutingModule { }