在下面的示例路由配置中,我试图了解如何使用路径的可变段重定向 . [259] . 在这种情况下:似乎无法找到id . 我引用了https://vsavkin.com/angular-router-understanding-redirects-2826177761fc,它描述了一个类似的用例,其中在redirectTo属性中使用动态段 .
使用启动的/ sso / ip / :id 路由中的:id参数来解析id吗?提出了类似的问题,但从未回复:https://groups.google.com/forum/#!topic/angular/Mw0N3qYphO8 .
非常感谢任何帮助?
const appRoutes: Routes = [
{
path: 'ip',
children: [
{
path: ':id',
children: [
{
path: 'tcv',
component: IpTcvComponent
},
{
path: '',
component: IpComponent
}
]
},
{
path: '',
component: IpHomeComponent
}
]
},
{
path: 'sso',
children: [
{
path: 'ip',
children: [
{
path: ':id',
children: [
{
path: 'tcv',
pathMatch: 'full',
redirectTo: '/ip/:id/tcv'
},
{
path: '',
pathMatch: 'full',
redirectTo: '/ip/:id'
}
]
},
{
path: '',
pathMatch: 'full',
redirectTo: '/ip'
}
]
}
]
}
];
1 回答
我的方法是手动处理重定向,如果我不能让路由配置工作 .
RedirectService
使用redirectInFlight()
方法侦听Router.events
observable . 当路由器尝试转到目标路径(例如/sso/ip/:id
)时,透明地重定向到正确的路径:/ip/:id
然后我将服务添加到
AppModule.providers
,在AppComponent
中注入服务,并调用redirectInFlight()
AppComponent
RedirectService
最后,您可以从路由器配置中删除整个
sso
路径及其子路径,从而简化了它 .Live demo
注意:此实现是一个起点 . 您可以通过存储和引用重定向 Map 而不是硬编码“/ sso”来使其更加健壮 .