Angular子路由参数匹配报错:NG04002路由无法匹配问题排查
Angular路由匹配错误原因及修复方案
问题根源
你的URL analyse/portugal/lisbon/demography/2022 无法匹配现有路由,核心原因是当前路由配置要求demography之后必须跟population或age前缀才能匹配年份参数:
- 现有子路由定义的是
population/:year和age/:year,意味着合法URL应该是analyse/portugal/lisbon/demography/population/2022或analyse/portugal/lisbon/demography/age/2022 - 你的URL直接在
demography后加了年份,没有对应前缀,所以触发NG04002路由不匹配错误
修复方案
根据你的需求,有两种修改方式:
方案一:让demography/:year直接匹配PopulationComponent
如果希望URL analyse/portugal/lisbon/demography/2022 直接指向PopulationComponent,需要调整路由结构,把年份参数提升为demography的直接子路由:
{ path: 'analyse', component: AnalyseComponent, canActivate: [AuthGuard], children: [ { path: 'portugal/:province/demography', component: DemographyComponent, children: [ {path: '', redirectTo: 'population', pathMatch: 'full'}, {path: ':year', component: PopulationComponent}, // 新增直接匹配年份的路由 {path: 'population/:year', component: PopulationComponent}, {path: 'age/:year', component: AgeComponent}, ] } ] }
这样配置后,demography/2022会直接匹配到PopulationComponent,同时保留population/2022和age/2022的路由规则。
方案二:修改URL匹配现有路由
如果你的需求就是访问人口数据的2022年统计,直接把URL改为:http://localhost:4200/analyse/portugal/lisbon/demography/population/2022
即可匹配现有路由中的population/:year规则。
内容的提问来源于stack exchange,提问作者Fatih Doğan
相关产品推荐
相关产品推荐

