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'
}
});
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With