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

Angular模块路由配置问题:子路由触发NotFound页面如何解决?

解决Angular子路由触发全局NotFound的问题

嘿,我瞅了下你的路由配置,问题出在yards子模块的路由路径前缀重复了!

问题根源

你在app-routing里已经把yards作为父路由路径,而yards-routing里的子路由又都加上了yards/前缀,这会导致Angular期望的访问路径变成yards/yards/1、yards/yards/new这类,但你实际访问的是yards/1、yards/new,自然匹配不到任何路由,最终触发顶层的**规则跳转到NotFound页面。

修改方案

1. 修正yards-routing的子路由配置

把子路由的路径改成相对路径(去掉yards/前缀),同时添加子模块内部的404处理:

const routes: Routes = [
  { path: '', component: YardListComponent}, // 匹配 /yards
  { path: 'new', component: YardEditComponent}, // 匹配 /yards/new
  { path: ':id', component: YardDetailComponent}, // 匹配 /yards/:id
  { path: ':id/edit', component: YardEditComponent}, // 匹配 /yards/:id/edit
  // 子模块内部的未知路径,可选择跳转到全局NotFound或自定义子级NotFound
  { path: '**', redirectTo: '/notfound' }
];

2. 补充其他模块的权限守卫(可选)

我注意到inspections和settings路由没有加canActivate: [AuthenticationGuard],如果这两个模块也需要登录才能访问,建议补上,保持权限规则一致:

// app-routing.ts 修改后
const routes: Routes = [
  { path: 'login', loadChildren: 'app/modules/auth/auth.module#AuthModule' },
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  { path: 'dashboard', loadChildren: 'app/modules/dashboard/dashboard.module#DashboardModule', canActivate: [AuthenticationGuard] },
  { path: 'yards', loadChildren: 'app/modules/yards/yards.module#YardsModule', canActivate: [AuthenticationGuard] },
  { path: 'inspections', loadChildren: 'app/modules/inspections/inspections.module#InspectionsModule', canActivate: [AuthenticationGuard] },
  { path: 'settings', loadChildren: 'app/modules/settings/settings.module#SettingsModule', canActivate: [AuthenticationGuard] },
  { path: 'notfound', loadChildren: 'app/modules/errors/errors.module#ErrorsModule' },
  { path: '**', redirectTo: 'notfound' }
];

原理说明

Angular的子路由是相对于父路由路径进行拼接匹配的:

  • 父路由yards + 子路由'' → /yards
  • 父路由yards + 子路由'new' → /yards/new
  • 父路由yards + 子路由':id' → /yards/:id

这样修改后,你访问yards/1、yards/new就能正确匹配到对应的组件;同时,顶层的**会处理全局未知路径(比如/random-path),子模块的**会处理子级未知路径(比如/yards/invalid-id),完美实现各级路由的NotFound触发逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:35:04