【问题标题】:Angular: set params in urlAngular:在 url 中设置参数
【发布时间】:2021-04-20 15:55:05
【问题描述】:

Angular 应用程序 > 更新 url 值。

我想做的是设置我的查询参数的一个特定值,而不更改其余部分,也无需导航到此网址。

例如,我的网址是

https://localhost:4200/some_page?x=0&y=1&z=2

我现在想要做的是将y 的值设置为不同的值,但不导航到它。我想简单地把它放在 url 字段中,没有任何副作用。

我已经找到了使用location 包的方法

  const params = { y : 10 };
  const url = this._router.createUrlTree([], { relativeTo: this._activatedRoute, queryParams: params }).toString();

  this._location.go(url);

但是这种方法会删除xz 的值。我也无法获取当前参数并设置特定值。例如。这是不可能的(我不完全知道为什么,documentation 没有声明它是只读的)

this._activatedRoute.queryParams.subscribe((params: Params) => {
  (params as any).y = 10;
  const url = this._router.createUrlTree([], { relativeTo: this._activatedRoute, queryParams: params }).toString();

  this._location.go(url);
});

我还必须注意,使用Router 不是一个选项,因为它仍然会发出导航事件,应用程序中的订阅正在执行他们不应该做的事情(因为它不是我想要的导航事件,只更新url中的一些参数)。

this._router.navigate([], {
  relativeTo: this._activatedRoute,
  queryParams: { x:1, y: 10, z: 1},
  queryParamsHandling: 'merge',
  skipLocationChange: true // or false, does not matter
});

【问题讨论】:

    标签: angular typescript


    【解决方案1】:
    this._router.navigate(['.'], {
      relativeTo: this._activatedRoute,
      queryParams: {
        x: "Xvalue",
        y: "Yvalue",
        z: "Zvalue"
      },
      queryParamsHandling: ''
    } );
    

    【讨论】:

    • 这仍然会触发 NavigationEnd 事件
    猜你喜欢
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    相关资源
    最近更新 更多