Chitraveer Akhil
Chitraveer Akhil

Reputation: 147

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?

Upvotes: 4

Views: 6552

Answers (3)

Kent Hamilton
Kent Hamilton

Reputation: 31

Try this:

let searchParams = new HttpParams();

for (const [k, v] of Object.entries(data)) {
  console.log(`${k}: ${v}`);
  if (v !== '' || v !== undefined) {
    searchParams = searchParams.append(k, v);
  }
}

Upvotes: 0

ForrestLyman
ForrestLyman

Reputation: 1652

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'));

Upvotes: 9

firegloves
firegloves

Reputation: 5709

The API are lightly differents, by this way you can send a dynamic request with params in query string

let paramsMap = new Map<any,any>();
paramsMap.set('username','admin');
paramsMap.set('password','admin');

let params = new HttpParams();
paramsMap.forEach((value: any, key: any) => {
  params = params.set(key, value);
});

return this.http.request<any>('post', this.url + LOGIN_URL, { 'params': params});

If you inspect HttpClient methods you can see how it works.

Answer to first comment:

HttpParams it's not immutable, it'used to pass params to query string. So what you need is this:

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

return this.http.post<any>(this.url + LOGIN_URL, mapToObject(paramsMap));

/**
 * recursive function that receive a Map and returns a JSON object
 * @param map
 * @returns {any}
 */
function mapToObject(map) {
  const out = Object.create(null)
  map.forEach((value, key) => {
    if (value instanceof Map) {
      out[key] = mapToObject(value)
    }
    else {
      out[key] = value
    }
  });
  return out
}

Upvotes: 3

Related Questions