问题
I have a URL with the query string id. But, the variable id can be come as 'id' or 'Id' in the 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:
http://xxx/abc?id=10
http://xxx/abc?Id=10
enter image description here
Other than this, is there any simple way to handle the case sensitive variables and take the values properly in angular4?
回答1:
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);
});
}
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;
}
With this:
private findQueryParams() {
this._route.queryParams.subscribe((params: Params) => {
const _params = toLower(params);
const idValue = params['id'] || '0';
let id = Number(params);
});
}
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.
回答2:
If you wish to have a component which shows a specific abc
item, then you should really be having your URLs without query parameters and embracing the concept of Routes instead
i.e. instead of having http://xxx/abc?id=10 to show the abc
item with an id of 10 you should just be having a route http://xxx/abc/10
You would then add this route as:
{ path: 'abc/:id', component: abcComponent },
where abcComponent is the component which shows the relevant item
来源:https://stackoverflow.com/questions/50098153/how-to-take-the-values-from-the-case-sensitive-query-param-variables