Angular 14配置**路由后特定组件跳转至404页面问题
问题解决:Angular配置
**路由后特定页面跳404 核心原因
Angular路由采用从上到下的顺序匹配机制,如果**通配符路由没有放在路由数组的最后一位,会优先匹配所有未明确定义的路由(包括你正确配置的otherStuff/:id),直接跳转到404页面。此外,子模块路由的注册方式、路由路径的匹配规则也可能引发该问题。
分步解决方案
1. 调整AppRouting中的路由顺序
打开app-routing.module.ts,确保**路由是数组的最后一项:
const routes: Routes = [ // 先放置所有明确匹配的路由,比如加载StuffModule的路由 { path: '', loadChildren: () => import('./stuff/stuff.module').then(m => m.StuffModule) }, // 其他业务路由... // 通配符路由必须放在最后 { path: '**', component: PageNotFoundComponent } ];
2. 检查StuffModule的路由配置
确认stuff-routing.module.ts中正确注册了otherStuff/:id路由:
const routes: Routes = [ { path: '', component: MainStuffComponent }, // 明确声明otherStuff路由 { path: 'otherStuff/:id', component: OtherStuffComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class StuffRoutingModule { }
3. 验证路由链接的正确性
在Component1B中,确保跳转链接的路径正确:
- 如果StuffModule挂载在根路径
''下,链接应为:<a routerLink="/otherStuff/1">Go to other stuff where 404 happens</a> - 如果StuffModule挂载在
/stuff路径下,链接应为:<a routerLink="/stuff/otherStuff/1">Go to other stuff where 404 happens</a>
4. 确认路由匹配策略(可选)
如果根路由存在空白路径,添加pathMatch: 'full'避免路由匹配歧义:
{ path: '', loadChildren: () => import('./stuff/stuff.module').then(m => m.StuffModule), pathMatch: 'full' }
额外排查点
- 检查StuffModule是否在AppModule中正确导入,或是否通过路由懒加载的方式加载(推荐懒加载)
- 确认
PageNotFoundComponent已在AppModule中声明或导入
内容的提问来源于stack exchange,提问作者TTT
相关产品推荐
相关产品推荐

