【发布时间】:2019-11-15 07:13:20
【问题描述】:
我有这样的路由配置:
[
{
path: 'parent',
component: ParentComponent,
children: [
{
path: 'child-one',
component: ChildOneComponent
},
{
path: 'child-two',
component: ChildTwoComponent
}
]
}
]
在ParentComponent 内,我有一个按钮,当单击该按钮时,应将查询参数添加到当前路由/URL。我找到了建议此解决方案的其他答案:
// inside ParentComponent
constructor(
private router: Router,
private route: ActivatedRoute
) { }
onButtonClick() {
this.router.navigate([], {
relativeTo: this.route,
queryParams: { myparam: true },
queryParamsHandling: 'merge',
})
}
但是,在ParentComponent 中使用此解决方案会导致导航相对于父路由,而不是子路由。因此,例如,如果用户位于 URL /parent/child-one 并单击按钮,浏览器将导航到 /parent?myparam=true 而不是 /parent/child-one?myparam=true。
由于此代码在我的应用程序的顶部组件中运行,我宁愿不进行遍历 ActivatedRoute 对象寻找传递给 relativeTo 参数的适当路径的麻烦事,因为有一个可能会出现很多边缘情况。
Router 对象确实在其url 属性中提供了完整的当前 URL,但是,像这样使用该 URL 不会触发导航事件:
onButtonClick() {
this.router.navigate([this.router.url], {
queryParams: { myparam: true },
queryParamsHandling: 'merge',
})
}
用this.router.navigateByUrl 尝试同样的事情也不会触发导航事件:
onButtonClick() {
this.router.navigateByUrl(this.router.url, {
queryParams: { myparam: true },
queryParamsHandling: 'merge',
})
}
将replaceUrl: true 添加到NavigationExtras 对象(navigateByUrl 的第二个参数)也不会导致导航事件。
【问题讨论】:
-
你可以尝试改用
this.router.navigateByUrl -
使用当前 URL 调用
this.router.navigateByUrl也不会触发导航事件。 -
你添加了 { replaceUrl: true } 参数吗?
-
是的,我尝试使用和不使用
replaceUrl参数。 -
对我来说这种方式是可行的`this.router.navigate([], { queryParams: { myparam: true }, relativeTo: this.activatedRoute, fragment: this.activatedRoute.snapshot.fragment, queryParamsHandling :'合并', });` .并且不管哪个组件调用它