我试图更新(添加,删除)queryParams从一个组件。在angularJS中,它曾经是可能的,这要归功于:

$location.search('f', 'filters[]'); // setter
$location.search()['filters[]'];    // getter

我有一个应用程序的列表,用户可以过滤,顺序等,我想设置在url的queryParams所有过滤器激活,这样他就可以复制/粘贴url或与他人共享。

但是,我不希望每次选择筛选器时都重新加载页面。

新路由器能做到吗?


当前回答

更好的是-只有HTML:

<a [routerLink]="

注意,数组是空的,而不是只做routerLink=""或[routerLink]=" "" "

其他回答

我最终把urlTree和location.go结合起来

const urlTree = this.router.createUrlTree([], {
       relativeTo: this.route,
       queryParams: {
           newParam: myNewParam,
       },
       queryParamsHandling: 'merge',
    });

    this.location.go(urlTree.toString());

不确定toString是否会导致问题,但不幸的是location。Go似乎是基于字符串的。

更好的是-只有HTML:

<a [routerLink]="

注意,数组是空的,而不是只做routerLink=""或[routerLink]=" "" "

Angular的Location服务应该在与浏览器的URL交互时使用,而不是用于路由。这就是为什么我们要使用位置服务。

angular HttpParams用于创建查询参数。请记住HttpParams是不可变的,这意味着在创建值时它必须被链接。

最后,使用this._location。replaceState更改为URL,而无需重新加载页面/路由和原生js位置。获取没有参数的url的路径,以每次重置参数。

constructor(
    private _location: Location,
) {}

...

updateURLWithNewParamsWithoutReloading() {
    const params = new HttpParams().appendAll({
        price: 100,
        product: 'bag'
    });

    this._location.replaceState(
        location.pathname,
        params.toString()
    );
}

如果你想改变查询参数而不改变路由。见下文 下面的例子可能对你有帮助: 当前路由为:/search &目标路由是(没有重载页面):/search?查询=爱

    submit(value: string) {
      this.router.navigate( ['.'],  { queryParams: { query: value } })
        .then(_ => this.search(q));
    }
    search(keyword:any) { 
    //do some activity using }

请注意:您可以使用this.router。导航(['search']而不是this.router。导航((“。”)

大多数人投票的答案在一定程度上对我有用。浏览器的url保持不变,但我的routerLinkActive在导航后不再工作。

我的解决方案是使用lotit .go:

import { Component } from "@angular/core";
import { Location } from "@angular/common";
import { HttpParams } from "@angular/common/http";

export class whateverComponent {
  constructor(private readonly location: Location, private readonly router: Router) {}

  addQueryString() {
    const params = new HttpParams();
    params.append("param1", "value1");
    params.append("param2", "value2");
    this.location.go(this.router.url.split("?")[0], params.toString());
  }
}

我使用HttpParams来构建查询字符串,因为我已经使用它与httpClient一起发送信息。但你可以自己构建。

this._router.url.split("?")[0],是从当前url中删除所有之前的查询字符串。