You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular嵌套路由默认跳转:访问/products自动导向/products/professional

Angular嵌套路由重定向解决方案

直接上正确的路由配置:

const routes: Routes = [
  // 这里可添加其他顶层路由
  {
    path: 'products',
    component: ProductsComponent, // 该组件模板必须包含子<router-outlet>标签
    children: [
      // 核心规则:访问/products时自动跳转到/products/professional
      { path: '', redirectTo: 'professional', pathMatch: 'full' },
      { path: 'professional', component: ProfessionalProductsComponent },
      { path: 'consumer', component: ConsumerProductsComponent }
    ]
  }
];

关键说明:

  • 重定向规则必须放在父路由的children数组内,用path: ''匹配父路由加载后无后续子路径的场景(即用户直接访问/products时)。
  • 必须指定pathMatch: 'full':Angular默认的prefix匹配会把空路径识别为所有子路由的前缀,导致重定向逻辑混乱,full能保证只有当路径完全为空时才触发跳转。
  • 确认ProductsComponent的模板里存在<router-outlet>,否则子路由组件无法正常渲染。

你之前的错误是把重定向规则放在了顶层路由层级(和products父路由同级),或者在父路由内直接配置redirectTo,这会和嵌套路由的逻辑冲突,因此Angular抛出NG04014错误。

内容的提问来源于stack exchange,提问作者sandrooco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 01:37:50