Angular懒加载模块场景下路由守卫获取父路由参数异常问题
Angular路由参数获取异常问题原因及解决方案
问题根因
- 懒加载的Page模块中子路由配置不符合Angular规范:子路由的
path禁止携带前导斜杠/,配置的path: '/hello'会被Angular识别为绝对路径路由,不会被当作page路由的子路由进行匹配,直接破坏了原有路由树的匹配逻辑。 - 路由匹配逻辑失效后,Angular无法正确将
/my-id/page/hello路径按预期匹配为/:id/page/hello的层级结构,反而会错误将路径最后一段hello匹配到顶层的动态参数:id位,导致守卫中拿到错误的参数值。
修复方案
- 修改Page模块的路由配置,去掉
hello路由path的前导斜杠:
const pageRoutes = [ { path: '', component: PageComponent, children: [ { path: 'hello', component: HelloComponent } ] } ]
- 如果后续需要在深层子路由/守卫中统一获取所有层级的路由参数,可以在根路由配置中添加参数继承策略:
@NgModule({ imports: [RouterModule.forRoot(routes, { paramsInheritanceStrategy: 'always' })], exports: [RouterModule] }) export class AppRoutingModule { }
内容的提问来源于stack exchange,提问作者Ewan
相关产品推荐
相关产品推荐

