Angular:如何在不更改路由的情况下更新queryParams [英] Angular: How to update queryParams without changing route

查看:118
本文介绍了Angular:如何在不更改路由的情况下更新queryParams的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从组件更新(添加,删除)queryParams.在angularJS中,由于:

I am trying to update (add, remove) queryParams from a component. In angularJS, it used to be possible thanks to :

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

我有一个带有列表的应用程序,用户可以对其进行过滤,订购等,我想在url的queryParams中设置所有已激活的过滤器,以便他可以复制/粘贴url或与其他人共享.

I have an app with a list that the user can filter, order, etc and I would like to set in the queryParams of the url all the filters activated so he can copy/paste the url or share it with someone else.

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

这对新路由器可行吗?

推荐答案

您可以使用新的查询参数导航到当前路线,这不会重新加载页面,但会更新查询参数.

You can navigate to the current route with new query params, which will not reload your page, but will update query params.

类似(在组件中)的东西:

Something like (in the component):

constructor(private router: Router) { }

public myMethodChangingQueryParams() {
  const queryParams: Params = { myParam: 'myNewValue' };

  this.router.navigate(
    [], 
    {
      relativeTo: activatedRoute,
      queryParams: queryParams, 
      queryParamsHandling: 'merge', // remove to replace all query params by provided
    });
}

请注意,尽管它不会重新加载页面,但会将新条目推送到浏览器的历史记录中.如果要在历史记录中替换它,而不是在历史记录中添加新值,则可以使用{ queryParams: queryParams, replaceUrl: true }.

Note, that whereas it won't reload the page, it will push a new entry to the browser's history. If you want to replace it in the history instead of adding new value there, you could use { queryParams: queryParams, replaceUrl: true }.

正如注释中已经指出的那样,在我的原始示例中缺少了[]relativeTo属性,因此它也可以更改路由,而不仅仅是查询参数.在这种情况下,正确的this.router.navigate用法将是:

As already pointed out in the comments, [] and the relativeTo property was missing in my original example, so it could have changed the route as well, not just query params. The proper this.router.navigate usage will be in this case:

this.router.navigate(
  [], 
  {
    relativeTo: this.activatedRoute,
    queryParams: { myParam: 'myNewValue' },
    queryParamsHandling: 'merge'
  });

将新参数值设置为null将从URL中删除参数.

Setting the new parameter value to null will remove the param from the URL.

这篇关于Angular:如何在不更改路由的情况下更新queryParams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆