4

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'
  }
});
Reid
  • 661
  • 1
  • 8
  • 25

1 Answers1

11

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');
Fredrik_Borgstrom
  • 2,504
  • 25
  • 32