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]); });
let httpParams = new HttpParams(); Object.keys(data).forEach(function (key) { httpParams = httpParams.append(key, data[key]); });
Since 5.0.0-beta.6 (2017-09-03) they added new feature (accept object map for HttpClient headers & params)
Going forward the object can be passed directly instead of HttpParams.
getCountries(data: any) { // We don't need any more these lines // let httpParams = new HttpParams(); // Object.keys(data).forEach(function (key) { // httpParams = httpParams.append(key, data[key]); // }); return this.httpClient.get("/api/countries", {params: data}) }
HttpParams is intended to be immutable. The set
and append
methods don't modify the existing instance. Instead they return new instances, with the changes applied.
let params = new HttpParams().set('aaa', 'A'); // now it has aaa params = params.set('bbb', 'B'); // now it has both
This approach works well with method chaining:
const params = new HttpParams() .set('one', '1') .set('two', '2');
...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.
let httpParams = new HttpParams().set('aaa', '111'); // now it has aaa httpParams.set('bbb', '222'); // result has both but is discarded
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