如何从区分大小写的查询参数变量中获取值? [英] How to take the values from the case sensitive query param variables?
问题描述
我有一个带有查询字符串 id 的URL.但是,变量 id 可以在URL中以'id'或'Id'的形式出现.
I have a URL with the query string id. But, the variable id can be come as 'id' or 'Id' in the URL.
根据我的理解,这两种方法将以不同的方式处理.为了处理以下URL,我编写了如所附屏幕快照中的代码:
As per my understanding, these 2 will be treated differently. For handling the following URL's, I have wrote the code as in the attached screenshot:
除此之外,是否有任何简单的方法来处理区分大小写的变量并在angular4中正确获取值?
Other than this, is there any simple way to handle the case sensitive variables and take the values properly in angular4?
推荐答案
正如@vogomatix所说,您不应该在同一个param中使用不同的名称.但是,无论出于何种原因,都可以像下面这样简化代码:
As @vogomatix said, you shouldn't have the same param with different names. But, if for whichever reason you do, you can simplfy your code a bit like this:
private findQueryParams() {
this._route.queryParams.subscribe((params: Params) => {
const idValue = params['id'] || params['Id'] || '0';
let id = Number(idValue);
});
}
这样,您将使用id
的值(如果不存在,则使用Id
),如果不存在,则使用'0'
This way you'll use the value of id
, if not exists, then Id
, and if doesn't exists, either, then you'll use '0'
如果您说的是更多组合,那么最好的选择是将参数克隆为小写版本:
If there can be more combinations, as you say, then your best option is to clone the params to a lowercase version:
function toLower(params: Params): Params {
const lowerParams: Params = {};
for (const key in params) {
lowerParams[key.toLowerCase()] = params[key];
}
return lowerParams;
}
与此:
private findQueryParams() {
this._route.queryParams.subscribe((params: Params) => {
const _params = toLower(params);
const idValue = params['id'] || '0';
let id = Number(params);
});
}
当然,每次从Router
获取参数时,您都必须做到这一点,但这是不可避免的,因为基本缺陷位于Url系统中.
Of course you've got to this every time you get params from the Router
, but that is unavoidable, as the base defect is in the Url system.
这篇关于如何从区分大小写的查询参数变量中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!