let httpParams = new HttpParams().set('aaa', '111');
httpParams.set('bbb', '222');
Why this doesn't work? It only set the 'aaa' and NOT the 'bbb'
Also, I have an object { aaa: 111, bbb: 222 } How can I set all the values without looping?
UPDATE (this seems to work, but how can avoid the loop?)
let httpParams = new HttpParams();
Object.keys(data).forEach(function (key) {
httpParams = httpParams.append(key, data[key]);
});
As for me, chaining
set
methods is the cleanest wayIn more recent versions of
@angular/common/http
(5.0 and up, by the looks of it), you can use thefromObject
key ofHttpParamsOptions
to pass the object straight in:This just runs a
forEach
loop under the hood, though:Another option to do it is:
HttpParams is intended to be immutable. The
set
andappend
methods don't modify the existing instance. Instead they return new instances, with the changes applied.This approach works well with method chaining:
...though that might be awkward if you need to wrap any of them in conditions.
Your loop works because you're grabbing a reference to the returned new instance. The code you posted that doesn't work, doesn't. It just calls set() but doesn't grab the result.