Jos*_*ana 17 angular2-routing angular
我正在努力在Angular 2.4.2中导航期间清除URL参数.我已尝试附加每个选项以清除下面导航线中的参数,或者使用导航或navigateByUrl中的任何混合,但无法弄清楚如何完成.
this.router.navigateByUrl(this.router.url, { queryParams: {}, preserveQueryParams: false });
Run Code Online (Sandbox Code Playgroud)
作为一个例子,我在路线,/section1/page1?key1=abc&key2=def
并希望保持在相同的路线,但删除所有的url参数,所以最终的结果应该是/section/page1
Jos*_*ana 16
正如DeborahK指出的那样,当我导航到this.router.url时,该URL已经嵌入了url params.为了解决这个问题,我将URL中的params作为字符串剥离,然后使用navigateByUrl跳转到那里.
let url: string = this.router.url.substring(0, this.router.url.indexOf("?"));
this.router.navigateByUrl(url);
Run Code Online (Sandbox Code Playgroud)
Deb*_*ahK 14
navigateByUrl
如果您将查询参数传递给没有查询参数的URL,则使用将删除查询参数.
或者你可以尝试:
this.router.navigate(this.router.url, { queryParams: {}});
Run Code Online (Sandbox Code Playgroud)
注意:navigate
而不是navigateByUrl
那样有用吗?
如果您不想重新加载页面,也可以使用 Location
import { Location } from '@angular/common';
[...]
this.location.replaceState(this.location.path().split('?')[0], '');
Run Code Online (Sandbox Code Playgroud)
this.location.path()
为您提供当前路径。您可以通过使用URL之前的URL中的所有内容重置页面路径来删除参数?
。
您可以添加replaceUrl: true
导航附加功能。这样,路由器将导航到同一页面,但您仍然保持在历史记录中的相同状态,并且 url 参数消失了,同时仍然允许您返回到之前的路由。
从文档:
this.router.navigate([], { replaceUrl: true});
Run Code Online (Sandbox Code Playgroud)
使用skipLocationChange选项,它不会显示参数:假设您的网址是
现在您的代码中的内容将查询参数设置为
?q = all&viewtype = total
如果没有skipLocationChange,则您在浏览器中的网址(在调用Navigation之后)将是:
与skipLocationChange:true它仍然存在
let qp = { q : "all" , viewtype : "total" }
this.router.navigate(['/view'], { queryParams: qp,skipLocationChange: true });
Run Code Online (Sandbox Code Playgroud)
这是一个简单的
this.router.navigate([], {});
Run Code Online (Sandbox Code Playgroud)
// 或者
this.router.navigate([], {
queryParams: {
param1:'',
param2:''
}
});
Run Code Online (Sandbox Code Playgroud)
这将清除 URL,无需硬编码,并且不会重新加载页面。
constructor(
private activatedRoute: ActivatedRoute,
private router: Router
)
...
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {},
replaceUrl: true,
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28341 次 |
最近记录: |