在这种情况下,我的网址类似于
https://example.com?a=1&b=2&c=3
现在我想将其更改为
https://example.com?a=1&b=2&c=4
我尝试过
const navigationExtras: NavigationExtras = {
queryParams: { c: 4}
};
this.router.navigate([], navigationExtras);
但是,如果我这样做,c
确实会更新,但是查询参数a
和b
会被删除。因此,我尝试添加preserveQueryParams: true
,但似乎您无法更改任何内容。关于如何仅更新一个查询参数的任何建议吗?
答案 0 :(得分:2)
只需在navigationExtras中再添加一个属性queryParamsHandling: 'merge'
,以保持不变的queryParams:-
const navigationExtras: NavigationExtras = {
queryParams: { c: 4},
queryParamsHandling: 'merge' // keep the old queryParams if they are not updated
};
this.router.navigate([], navigationExtras);
另一种方式:-
否则,您将需要为未更改的queryParams保留旧值。因此,您可以像这样:-
const navigationExtras: NavigationExtras = {
queryParams: {
...this._ActivatedRoute.snapshot.queryParams, // get the queryParams from the ActivatedRoute
...{c: 4} // and then update what you want
}
};
然后执行与您相同的过程。
要从queryParams
获得ActivatedRoute
,您需要先注入它:-
constructor(
private _ActivatedRoute: ActivatedRoute // here
) {}
答案 1 :(得分:-1)
您可以尝试
constructor(
private router: Router,
private route: ActivatedRoute,
) {}
changeQuery() {
this.router.navigate(['.'], { relativeTo: this.route, queryParams: { ... }});
}