Angular 的路由功能在构建复杂单页应用(SPA)时至关重要。以下是关于高级路由的核心知识点:

1. 路由模块与子路由

  • 使用 RouterModule.forRoot 配置主路由
  • 子路由通过 children 属性嵌套实现
  • 示例:
    const routes: Routes = [
      {
        path: 'dashboard',
        component: DashboardComponent,
        children: [
          { path: 'stats', component: StatsComponent },
          { path: 'settings', component: SettingsComponent }
        ]
      }
    ];
    
    angular_routing_advanced

2. 路由守卫(Route Guards)

  • CanActivate:控制路由访问权限
  • CanLoad:延迟加载路由模块
  • Resolve:预加载路由数据
  • 使用场景:权限验证、数据预加载、防止重复加载等

3. 路由懒加载(Lazy Loading)

  • 按需加载模块提升首屏性能
  • 示例:
    const routes: Routes = [
      { 
        path: 'lazy', 
        loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) 
      }
    ];
    
    lazy_loading_angular

4. 路由参数与数据

  • 使用 params 获取动态路由参数
  • 通过 data 传递静态数据
  • 示例:
    { 
      path: 'user/:id', 
      component: UserComponent, 
      data: { title: '用户详情' } 
    }
    

5. 路由重定向与空路径

  • 配置默认跳转:
    { 
      path: '', 
      redirectTo: '/home', 
      pathMatch: 'full' 
    }
    

想要深入了解基础路由配置?请访问 /angular/routing_basic 获取入门指南。