Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
  }
});
like image 755
Reid Avatar asked Jan 27 '23 20:01

Reid


1 Answers

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');
like image 123
Fredrik_Borgstrom Avatar answered Jan 30 '23 14:01

Fredrik_Borgstrom