Angular 10 的路由系统(@angular/router
)是构建单页应用的核心模块,支持动态路由、嵌套路由、懒加载等高级功能。以下是关键知识点:
1. 模块化路由配置
- 使用
RouterModule.forRoot()
配置主路由模块 - 示例代码:
const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent } ];
2. 懒加载(Lazy Loading)
- 通过
loadChildren
实现路由模块按需懒加载 - 优化性能,减少初始加载时间
- 示例:
{ path: 'features', loadChildren: () => import('./features/features.module').then(m => m.FeaturesModule) }
3. 路由守卫(Route Guards)
CanActivate
控制路由访问权限Resolve
预加载数据CanLoad
延迟加载模块- 适用场景:权限验证、数据预处理等
4. 动态路由与参数
- 使用
:param
定义动态路由 - 示例:
{ path: 'user/:id', component: UserProfileComponent }
- 参数通过
ActivatedRoute
获取
5. 扩展学习
- Angular 路由官方文档 提供完整 API 参考
- 深入理解 Angular 路由机制 可查看高级用法
📌 注意:Angular 10 已弃用
RouterModule.forChild()
的useHash
选项,建议使用RouterModule.forRoot()
配置useHash: true
替代。