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]);
});
Since HTTP Params class is immutable therefore you need to chain the set method:
Before 5.0.0-beta.6
Since 5.0.0-beta.6
Using this you can avoid the loop.
Furthermore, I suggest making toHttpParams function in your commonly used service. So you can call the function to convert the object to the HttpParams.
Update:
This is the other reason if you have used one common function like toHttpParams mentioned above, you can easily remove it or do changes if required.
As far as I can see from the implementation at https://github.com/angular/angular/blob/master/packages/common/http/src/params.ts
You must provide values separately - You are not able to avoid your loop.
There is also a constructor which takes a string as a parameter, but it is in form
param=value¶m2=value2
so there is no deal for You (in both cases you will finish with looping your object).You can always report an issue/feature request to angular, what I strongly advise: https://github.com/angular/angular/issues
PS: Remember about difference between
set
andappend
methods ;)2 Easy Alternatives
Since @MaciejTreder confirmed that we have to loop, here's a wrapper that will optionally let you add to a set of default params:
You can use it like so: