如何导航到相同的 URL 但更改(或添加,如果错过)查询参数之一

How to navigate to the same URL but change (or add if missed) one of the query params

有没有简单的方法可以实现?

例如我想set/change查询参数qp到值111:

/p1/ ----> /p1/?qp=111
/p2/ ----> /p2/?qp=111
/p1/?ee=22 ----> /p1/?ee=22&qp=111
/p1/?ee=22&qp=222 ----> /p1/?ee=22&qp=111

等等

我试过router.navigate([], { queryParams: { qp: '111' } }); 但它只是用 qp=111 替换所有查询参数,如果我设置 queryParamsHandling: 'preserve' URL 根本没有改变...

您可以与当前查询参数合并。

要获取它们,请将 ActivatedRouteSnapshot 作为 routeSnap 注入并作为

访问查询参数
const oldParams = this.routeSnap.queryParams

您还可以通过注入 ActivatedRoute 并使用 this.route.snapshot.queryParams 访问查询参数来获取此对象。

在你的例子中,这会给你:

/p1/              ----> {}
/p2/              ----> {}
/p1/?ee=22        ----> {ee: 22}
/p1/?ee=22&qp=222 ----> {ee: 22, qp: 222}

现在您可以通过与该对象合并进行导航。

this.router.navigate([], {...oldParams, qp: 11})

首先,我们需要获取现有的查询参数

const queryParams: Params = Object.assign({}, this.activatedRoute.snapshot.queryParams);

// Do something with the params
queryParams['myParam'] = 'myNewValue';

this.router.navigate(['.'], { queryParams: queryParams });

您需要通过当前的 ActivatedRoute

import { ActivatedRoute } from '@angular/router';

  constructor(
    private activatedRoute: ActivatedRoute
  ) {
    this.routeSnapshot = activatedRoute.snapshot['_routerState'].url;
  }

  this.router.navigate([this.routeSnapshot], {queryParams: { qp: '111' }});