我正在努力在 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 中的参数作为字符串剥离,然后使用 navigatorByUrl 跳转到那里。
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选项,它不会显示参数: 假设你的网址是
现在你的代码中有一些东西 将查询参数设置为
?q=全部&viewtype=总计
如果没有skipLocationChange,您在浏览器中的网址(调用导航后)将是:
使用skipLocationChange:true,它仍然存在
let qp = { q : "all" , viewtype : "total" }
this.router.navigate(['/view'], { queryParams: qp,skipLocationChange: true });
这是一个简单的
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,
});
从 Angular 7.2 开始,您可以使用状态
正在发送
this.router.navigate(['routename'], { state: { param1: 'bar' } });
收货
let paramobj = history.state;
console.log(paramobj.param1);
通过这个,您甚至可以从模板发送大型复杂对象。
我已经更新了@Joshua Ohana 答案一点点:
const getRouterPathUrl = (fullUrl: string): string => (fullUrl.includes("?") ? fullUrl.substring(0, fullUrl.indexOf("?")) : fullUrl);
this.router.navigate([getRouterPathUrl(this.router.url)],
{
queryParams: params,
replaceUrl: true
}
);
这样,您将能够在应用程序发生任何更改时更新和清除查询参数。