模块配置路由
创建带路由的模块
使用 --routing
参数创建带有路由的模块user:
ng g module module/user --routing
在路由中配置懒加载模块
在根模块的路由中以懒加载方式配置模块:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
// 在app.module.ts中加入相关模块后,路由中不再在前面直接引入,配置成懒加载模式
const routes: Routes = [
// 旧版Angular配置方式:loadChildren: '模块#模块的类'
// {path: 'user', loadChildren: './module/user/user.module#UserModule'},
// 新版Angular的配置方式:loadChildren: () => import('模块').then(m => m.模块的类)
{path: 'user', loadChildren: () => import('./module/user/user.module').then(m => m.UserModule)},
{path: 'product', loadChildren: () => import('./module/product/product.module').then(m => m.ProductModule)},
{path: 'artical', loadChildren: () => import('./module/artical/artical.module').then(m => m.ArticalModule)},
{path: '**', redirectTo: 'product'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
配置自定义模块的组件路由
- 在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 { }
2.
在product.routing.ts中以嵌套路由方式配置组件
```typescript
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ProductComponent } from './product.component';
import { PlistComponent } from './components/plist/plist.component';
import { CartComponent } from './components/cart/cart.component';
import { PcontentComponent } from './components/pcontent/pcontent.component';
// 在app.module.ts中配置了product模块的路由为'product',product模块内的路由访问时前面要加'/product'
const routes: Routes = [
{path: '', component: ProductComponent, // 访问http://localhost:4200/product
// 配置ProductComponent组件的嵌套子路由,可在ProductComponent组件的html中使用<router-outlet>标签展示
children: [
{path: 'plist', component: PlistComponent},
{path: 'cart', component: CartComponent},
{path: 'pcontent', component: PcontentComponent}
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ProductRoutingModule { }