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

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

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

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

新路由器能做到吗?


当前回答

@ radossawroszkowiak的答案几乎是正确的,除了相对于:这个。路线要求如下:

constructor(
    private router: Router,
    private route: ActivatedRoute,
) {}

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

其他回答

Try

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

将工作于同一路线导航,而不是单引号。

如果你想改变查询参数而不改变路由。见下文 下面的例子可能对你有帮助: 当前路由为:/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。导航((“。”)

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

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

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

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

你也可以像这样添加行为主体:

refresher$ = new BehaviorSubject(null);

我改变了我的代码:

this.route.queryParamMap.subscribe(some code)

to:

combineLatest([
    this.route.queryParamMap,
    this.refresher$
])
  .pipe(
     map((data) => data[0])
  )
  .subscribe(here is your the same code)

当你需要刷新订阅时,你需要调用这个:

this.refresher$.next(null);

不要忘记添加unsubscribe from the ngOnDestroy

@ radossawroszkowiak的答案几乎是正确的,除了相对于:这个。路线要求如下:

constructor(
    private router: Router,
    private route: ActivatedRoute,
) {}

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