繁体   English   中英

Angular2,如何清除路由器导航上的 URL 查询参数

[英]Angular2, how to clear URL query params on router navigate

我在 Angular 2.4.2 的导航期间努力清除 URL 参数。 我已尝试附加每个选项以清除以下导航行中的参数,或其中与导航或导航的任何混合,或navigateByUrl,但无法弄清楚如何完成。

this.router.navigateByUrl(this.router.url, { queryParams: {}, preserveQueryParams: false });

举个例子,我在路由/section1/page1?key1=abc&key2=def并希望保持在同一路由但删除所有 url 参数,所以最终结果应该是/section/page1

正如 DeborahK 指出的那样,当我导航到 this.router.url 时,该 URL 已经嵌入了 url 参数。 为了解决这个问题,我将 URL 中的参数作为字符串剥离,然后使用 navigateByUrl 跳转到那里。

let url: string = this.router.url.substring(0, this.router.url.indexOf("?"));
this.router.navigateByUrl(url);

如果您向它传递一个没有查询参数的 URL,则使用navigateByUrl将丢弃查询参数。

或者你可以试试:

this.router.navigate(this.router.url, { queryParams: {}});

注意: navigate而不是navigateByUrl

那样有用吗?

如果您不想重新加载页面,也可以使用Location

import { Location } from '@angular/common';
[...]
this.location.replaceState(this.location.path().split('?')[0], '');

this.location.path()为您提供当前路径。 您可以通过使用?之前的 URL 中的所有内容重置页面路径来删除参数? .

您可以在导航附加功能中添加replaceUrl: true 这样,路由器将导航到同一页面,但您仍然保持在历史记录中的相同状态,并且 url 参数消失了,同时仍然允许您返回到之前的路由。

从文档:

在替换历史记录中的当前状态时进行导航。

this.router.navigate([], { replaceUrl: true});

使用 skipLocationChange 选项,它不会显示参数:假设您的网址是

http://本地主机/视图

现在您的代码中的某些内容将查询参数设置为

?q=all&viewtype=total

如果没有skipLocationChange,您在浏览器中的网址(调用导航后)将是:

http://localhost/view?q=all&viewtype=total

使用 skipLocationChange : true 它仍然存在

http://本地主机/视图

let qp = { q : "all" , viewtype : "total" } 
this.router.navigate(['/view'], {  queryParams: qp,skipLocationChange: true });

从 angular 7.2 开始,您可以使用 state

发送

this.router.navigate(['routename'], { state: { param1: 'bar' } });

接收

let paramobj = history.state;
console.log(paramobj.param1);

通过这种方式,您甚至可以从模板发送大型复杂对象。

这是一个简单的

this.router.navigate([], {});

// 或者

this.router.navigate([], {
  queryParams: {
   param1:'',
   param2:''
  }
 });

这将清除没有硬编码的 URL,并且不会重新加载页面。

constructor(
        private activatedRoute: ActivatedRoute,
        private router: Router
    )
...
     this.router.navigate([], {
                relativeTo: this.activatedRoute,
                queryParams: {},
                replaceUrl: true,
            });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM