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

查看:45
本文介绍了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.

类似(在组件中):

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天全站免登陆