Search code examples
angulartypescriptquery-string

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


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 following:

http://xxx/abc?id=10

http://xxx/abc?Id=10

private findQueryParams() {
  this._router.queryParams.subscribe((params: Params) => {
    if (Object.keys(params).length) {
      let id = 0;
      if (params['id']) {
        id = Number(params['id']);
      } else if (params['Id']) {
        id = Number(params['Id']);
      }
    }
  });
}

Other than this, is there any simple way to handle the case sensitive variables and take the values properly in angular4?


Solution

  • 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.