[英]Angular 5 remove query param
如何从 URL 中删除查询参数? 例如从www.expample.com/home?id=123&pos=sd&sd=iii
到www.expample.com/home?id=123&sd=iii
编辑:这是我的版本:
this.activatedRoute.queryParams.subscribe(c => {
const params = Object.assign({}, c);
delete params.dapp;
this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: params });
}).unsubscribe();
您可以通过使用queryParamsHandling
的merge
选项并为要删除的任何参数传入null
来删除查询参数。
// Remove query params
this.router.navigate([], {
queryParams: {
'yourParamName': null,
'youCanRemoveMultiple': null,
},
queryParamsHandling: 'merge'
})
此选项更简单,需要更少的工作来确保您不会删除其他参数。 当您的组件被销毁时,您也无需担心清理可观察订阅。
更新: @epelc 下面的回答是最新且正确的方法: https : //stackoverflow.com/a/52193044/5932590。
不幸的是,目前没有明确的方法可以做到这一点: https : //github.com/angular/angular/issues/18011 。 然而,正如 jasonaden 对链接线程的评论,
这可以通过合并新旧查询参数手动完成,删除您不想要的键。
这是一种方法:
假设您将 queryParams 存储在某些属性中。
class MyComponent() {
id: string;
pos: string;
sd: string;
constructor(private route: ActivatedRoute, private router: Router) {}
ngOnInit() {
this.route.url.subscribe(next => {
const paramMap = next.queryParamMap;
this.id = paramMap.get('id');
this.pos = paramMap.get('pos');
this.sd = paramMap.get('sd');
});
}
}
清除pos
参数的方法如下所示:
clearPosParam() {
this.router.navigate(
['.'],
{ relativeTo: this.route, queryParams: { id: this.id, sd: this.sd } }
);
}
这将有效地导航到当前路线并清除您的pos
查询参数,使您的其他查询参数保持不变。
这是我找到的最好的 solotion,您可以更改 url 参数
在构造函数中使用
private _ActivatedRoute: ActivatedRoute
然后在 init 或构造函数体中使用它
var snapshot = this._ActivatedRoute.snapshot;
const params = { ...snapshot.queryParams };
delete params.pos
this.router.navigate([], { queryParams: params });
删除查询参数:
import { Router, ActivatedRoute, Params } from '@angular/router';
constructor(private router: Router, private activatedRoute: ActivatedRoute){
}
setQueryParams(){
const qParams: Params = {};
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: qParams,
queryParamsHandling: ''
});
}
您可以使用原生 javascript 操作从 url 中删除 queryParams 并使用navigateByUrl
方法导航到 View
https://angular.io/api/router/Router#navigateByUrl
this.route.queryParams
.subscribe((params: Params) => {
if (params && Object.keys(params).length > 0) {
const urlWithoutQueryParams = this.router.url.substring(0, this.router.url.indexOf('?'));
this.router.navigateByUrl(urlWithoutQueryParams)
.then(() => {
// any other functionality when navigation succeeds
params = null;
});
}
});
我写了一些路由器原型覆盖,使事情更容易处理查询参数:
这个想法是在路由器上调用一个方法来通过参数轻松管理路由,而不必每次都导出函数/重新声明功能。
创建一个包含原型覆盖定义的index.d.ts
文件:
// Ensure this is treated as a module.
export { };
declare module '@angular/router' {
interface Router {
updateQueryParams(activatedRoute: ActivatedRoute, params: Params): Promise<boolean>;
setQueryParams(activatedRoute: ActivatedRoute, params: Params): Promise<boolean>;
removeQueryParams(activatedRoute: ActivatedRoute, ...keys: string[]): Promise<boolean>;
}
}
重要:
确保在使用此原型覆盖之前导入此文件,我刚刚将我的原型导入添加到
app.module.ts
:
import './shared/prototype-overrides/router.prototypes';
这只会设置指定的查询参数,而不会合并参数。
您在以下路线上:
http://localhost:4200/#/some-route?param1=Test¶m2=test2
你要设置的查询参数, param3=HelloWorld
,删除他人。
this.router.setQueryParams(this.activatedRoute, { param3: 'HelloWorld' });
// Will route to http://localhost:4200/#/some-route?param3=HelloWorld
Router.prototype.setQueryParams = function (activatedRoute: ActivatedRoute, params: Params): Promise<boolean> {
const context: Router = this;
if (isNullOrUndefined(activatedRoute)) {
throw new Error('Cannot update the query parameters - Activated Route not provided to use relative route');
}
return new Promise<boolean>((resolve) => {
setTimeout(() => {
resolve(context.navigate([], {
relativeTo: activatedRoute,
queryParams: params
}));
});
});
};
这用于轻松更新 queryParams,它将合并路由中的查询参数,因此您没有重复的查询参数。
您在以下路线上:
http://localhost:4200/#/some-route?param1=Test¶m2=test2
并且您只想更新一个查询参数, param1
到param1=HelloWorld
,而其他保持原样。
this.router.updateQueryParams(this.activatedRoute, { param1: 'HelloWorld' });
// Will route to http://localhost:4200/#/some-route?param1=HelloWorld¶m2=test2
Router.prototype.updateQueryParams = function (activatedRoute: ActivatedRoute, params: Params): Promise<boolean> {
const context: Router = this;
if (isNullOrUndefined(activatedRoute)) {
throw new Error('Cannot update the query parameters - Activated Route not provided to use relative route');
}
// setTimeout required because there is an unintended behaviour when rapidly firing router updates in the same repaint cycle:
//
// NavigationCancel - Navigation ID 2 is not equal to the current navigation id 3
// https://stackoverflow.com/a/42802182/1335789
return new Promise<boolean>((resolve) => {
setTimeout(() => {
resolve(context.navigate([], {
relativeTo: activatedRoute,
queryParams: params,
queryParamsHandling: 'merge'
}));
});
});
};
您在以下路线上:
http://localhost:4200/#/some-route?param1=Test¶m2=test2¶m3=test3
并且您只想删除一个(或多个,由字符串分隔的键)查询参数param1
,而其他保持原样。
this.router.removeQueryParams(this.activatedRoute, 'param1');
// Will route to http://localhost:4200/#/some-route?param2=test2¶m3=test3
//Removing multiple parameters:
this.router.removeQueryParams(this.activatedRoute, 'param1', 'param3');
// Will route to http://localhost:4200/#/some-route?param2=test2
Router.prototype.removeQueryParams = function (activatedRoute: ActivatedRoute, ...keys: string[]): Promise<boolean> {
const context: Router = this;
const currentParams: any = {};
Object.keys(activatedRoute.snapshot.queryParams).forEach(key => {
currentParams[key] = activatedRoute.snapshot.queryParams[key];
});
keys?.forEach(key => {
delete currentParams[key];
});
return new Promise<boolean>((resolve) => {
setTimeout(() =>
resolve(context.setQueryParams(activatedRoute, currentParams))
);
});
};
这对我有用:
第 1 步:声明一个全局 url 搜索参数。
incomingUrlParams: URLSearchParams;
第 2 步:将查询保存在 urlsearchparam 全局变量中
this.incomingUrlParams = new URLSearchParams(window.location.search);
第 3 步:保存参数后在任何地方调用它:
clearQueryParamenters() {
let queryParamsJsonString: string = "";
this.incomingUrlParams.forEach(function(value, key) {
queryParamsJsonString += '"' + key + '":' + null + ',';
});
queryParamsJsonString = "{" + queryParamsJsonString.trim().replace(/(^,)|(,$)/g, "") + "}";
this.router.navigate([], {
queryParams: JSON.parse(queryParamsJsonString),
queryParamsHandling: 'merge'
})
}
我正在寻找完全做到这一点,但不使用路由器。 这是我想出的:
import { Location } from '@angular/common';
import { HttpParams } from '@angular/common/http';
declare location: Location; // get this from dependency injection
const [path, query] = location.path().split('?');
const params = new HttpParams({ fromString: query });
const theValueIWant = params.get('theParamIWant');
location.replaceState(path, params.delete('theParamIWant').toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.