我想提供一个基于查询参数重定向到给定页面的路径。例如:
/redirect?page=hero&id=1
应该重定向到:
/hero/1
在路由配置中有没有办法做到这一点?类似的东西:
{ path: 'redirect?page&id', redirectTo: ':page/:id' }
我可以让 redirectTo 尊重路径参数但不尊重查询参数。有什么想法吗?
答案 0 :(得分:0)
不,配置无法做到这一点。你看,Angular的路由器没有明确定义查询参数 - 任何url都可以有任意数量的查询参数,路径'/ page / id'和'/ page / id?key = value'在Angular中被视为相同并映射到相同的组件。还有其他更繁琐的解决方法。一种是根据组件的ActivatedRoute.queryParams
方法中的ngOnInit
Observable创建一个虚拟组件并重定向。你可以很容易地看出为什么这是一个坏主意。
另一种方法是创建一个解析器,这样你也可以根据ActivatedRoute.queryParams
Observable来解除组件声明并重新定位解析器,这似乎更清晰。
但我真的不明白为什么人们需要在前端应用程序中使用这样的路由,如果你想让某人访问'/ page / id',那么只需将它们导航到页面,而不需要任何中间技巧。
答案 1 :(得分:0)
您可以尝试使用redirectTo: '/:page/:id'
并使用自定义UrlMatcher()
提取您的网址page
和id
值:
...
const appRoutes: Routes = [
{
path: 'hero/:id',
component: TestComponent
},
{
matcher: redirectMatcher,
redirectTo: '/:page/:id'
}
];
...
/**
* custom url matcher for router config
*/
export function redirectMatcher(url: UrlSegment[]) {
if (url[0] && url[0].path.includes('redirect')) {
const path = url[0].path;
// sanity check
if (path.includes('page') && path.includes('id')) {
return {
consumed: url,
posParams: {
page: new UrlSegment(path.match(/page=([^&]*)/)[1], {}),
id: new UrlSegment(path.match(/id=([^&]*)/)[1], {})
}
}
}
}
return null;
}
STACKBLITZ:https://stackblitz.com/edit/angular-t3tsak?file=app%2Ftest.component.ts
使用redirectTo: ...
时还有另一个问题,主动链接未更新,实际isActive
标志未设置为true
,当我的stackblitz上显示acrive重定向链接时红色的