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

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

或者您可以尝试:

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

注意:navigate 而不是 navigateByUrl

这样行吗?

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

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

使用 skipLocationChange 选项,它不会显示参数: 假设你的 url 是

http://localhost/view

现在你的代码中有一些东西 将查询参数设置为

?q=all&viewtype=total

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

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

使用 skipLocationChange : true 它仍然存在

http://localhost/view

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

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

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

this.location.path() 为您提供当前路径。您可以通过在 ?.

之前使用 URL 中的所有内容重置页面路径来删除参数

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

来自文档:

Navigates while replacing the current state in history.

this.router.navigate([], { replaceUrl: 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,
            });