Search code examples
angularangular6angular-httpclienthttp-parameters

Conditionally adding parameters using HttpParams and FromObject and using a variable for the key name


Is there a way to conditionally add a parameter using HttpParams and fromObject? I tried adding the conditional parameter after instantiating the HttpParams but that didn't work:

const params = new HttpParams({
  fromObject : {
    requiredParam: 'requiredParam'
  }
});

if (addOptionalParam)
      params.append('optionalParamKey', 'optionalParamValue');

Also, can I use a constant variable as the key for the fromObject parameter? I tried this and it doesn't work:

  const ConstantVariableForKeyName = 'key';
  const params = new HttpParams({
  fromObject : {
    {{ConstantVariableForKeyName}}: 'paramValue'
  }
});

Solution

  • The HttpParams class is immutable, so any add or append operation returns a new object. Hence your params variable can NOT be a const, change it to let.

    Then, simply set your params to the returned value each time you need to manipulate it:

    let params = new HttpParams({
      fromObject : {
        requiredParam: 'requiredParam'
      }
    });
        if (addOptionalParam)
              params = params.append('optionalParamKey', 'optionalParamValue');
    

    Regarding your second question, use set or append instead, like this:

    const constParamKey = 'myKey';
     params = params.append(constParamKey , 'Value');