8

I have exactly angular version 4.3.2 and I cannot update because of dependencies. So for now I stick to this version. I have object with dynamic params (there can be other keys and values inside):

let query = {
    param1: 1,
    param2: 'a'
}

and I want to do something like:

params = new HttpParams();
params = params.append(query);
return this.httpClient.get(this.config.apiUrl + '/items', {
            params: params,
            headers: headers
        });

but there is not such params.append(query) method. So I need to iterate over the query keys and to add them one by one to the params. Is there easier solution for this?

Edit1:

according this answer this can be done since angular 5.0.0-beta.6 (2017-09-03), but is not solution for me. https://stackoverflow.com/a/46317900/1995258

kian
  • 1,449
  • 2
  • 13
  • 21
makkasi
  • 6,328
  • 4
  • 45
  • 60

4 Answers4

16

It can be done by using fromObject property

const params = {
    email:'abc@xyz.com',
    password:'qwerty'
}

const body = new HttpParams({fromObject: params})
H S W
  • 6,310
  • 4
  • 25
  • 36
  • The value of `fromObject` has type restrictions: either (1) all the keys and values must be strings or (2) it must be a `ReadonlyArray`. cf. https://angular.io/api/common/http/HttpParamsOptions#fromObject – JellicleCat Apr 16 '21 at 02:23
5

I solved it that way:

const params: HttpParams = new HttpParams().set('filters', JSON.stringify(filters));
pzaenger
  • 11,381
  • 3
  • 45
  • 46
Danilo Santos
  • 76
  • 1
  • 3
  • 1
    Object.keys(params).forEach(function (key) { httpParams = httpParams.append(key, JSON.stringify(params[key])); }); – makkasi Sep 16 '21 at 06:05
0
    let query = {
    param1: 1,
    param2: 'a'
}
    params = new HttpParams();
    params = params.appendAll(query);
    return this.httpClient.get(this.config.apiUrl + '/items', {
                params: params,
                headers: headers
            });

You can also achive this way

saddamhr
  • 11
  • 3
0

it will be work

let params = new HttpParams();
params = params.append('param1', '1' )
params = params.append('param2', 'a' )

Get URL be like

this.HttpClient.get(this.config.apiUrl + '/items', { params:params}).subscribe(
(response)=>{
   console.log(response)
})