How to take the values from the case sensitive query param variables?

痞子三分冷 提交于 2019-12-24 15:50:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!