Angular 的路由系统是实现单页应用(SPA)导航的核心功能,通过 RouterModule
和 Route
配置,开发者可以灵活管理页面跳转与组件加载。以下是关键知识点梳理:
📌 1. 模块化路由
将路由配置集中到 AppRoutingModule
中,通过 forRoot
方法注册全局路由:
const routes: Route[] = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
🧭 2. 路由配置基础
- 路径匹配:
path
定义 URL 路径,component
绑定对应组件 - 重定向:
redirectTo
实现默认页面跳转 - 懒加载:
loadChildren
分割代码包,提升首屏性能 - 路由守卫:
canActivate
控制访问权限
示例配置:
{
path: 'dashboard',
loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule)
}
📦 3. 路由参数传递
通过 params
获取动态数据:
this.route.paramMap.subscribe(params => {
console.log(params.get('id')); // 获取路径参数
});
🔄 4. 嵌套路由实践
在父组件模板中使用 <router-outlet>
嵌套子路由:
const routes: Route[] = [
{
path: 'user',
component: UserComponent,
children: [
{ path: 'profile', component: UserProfileComponent },
{ path: 'posts', component: UserPostsComponent }
]
}
];
📝 扩展阅读
如需深入了解 Angular 路由高级用法,可参考:
/angular/advanced-routing
📌 注意事项
- 路由路径应保持简洁,避免过度嵌套
- 使用
RouterModule
时需确保模块正确导入 - 动态路由结合
paramMap
可实现数据驱动的 UI 更新