Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically setting the HttpParams() body

In Angular 5 HttpClient I can set HttpParams() in this way.

const body = new HttpParams()
    .set('email', '[email protected]')
    .set('password', 'pass');

But while I try to set HttpParams() in this way. The values are not being set.

const paramsMap = new Map<any, any>();
paramsMap.set("email", "[email protected]");
paramsMap.set("password", "pass");

paramsMap.forEach((value: any, key: any) => {
    body.set(key, value);
});

Why it is not getting set? And how can I do that in similar way?

like image 685
Chitraveer Akhil Avatar asked Sep 01 '25 01:09

Chitraveer Akhil


1 Answers

HttpParams are immutable, so each time you use the set() method it returns a new instance. You can work around this by updating the reference:

const params = {
  test: 'true'
}

let httpParams = new HttpParams();

Object.keys(params).forEach(k => {
  httpParams = httpParams.set(k, params[k]);
});

console.log(httpParams.get('test'));
like image 74
ForrestLyman Avatar answered Sep 02 '25 16:09

ForrestLyman