Angular> = 4.3, httpClient.get parameters are empty
I am trying to migrate my requests Http
to requests HttpClient
. I was able to migrate my requests post
, but get
I got a problem before migrating the requests . When I do this, my backend does not receive any parameters accordingly, it tells me that the parameters are not specified and are empty.
Did I do something wrong?
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
constructor(private httpClient: HttpClient) {}
findItems() {
let params: HttpParams = new HttpParams();
params.set('something', 'hello');
this.httpClient.get<any[]>('http://localhost:3000/apath/', {params})
.subscribe((results: any[]) => {
console.log(results);
}, (errorResponse: any) => {
console.error(errorResponse);
});
}
Any idea?
source to share
Currently HttpParams
unchanged, you must set the parameters as shown below:
// for set method
let params: HttpParams = new HttpParams().set('something', 'hello');
// for append method
let params: HttpParams = new HttpParams().append('something', 'hello');
HttpParams method set
and append
overwrite the original copy of params
the newly updated on set
and append
and finally, returns a new instance.
So, we can do it in a few lines like below:
let params: HttpParams = new HttpParams();
params = params.set('something', 'hello');
params = params.append('something2', 'hello2');
Important:
Since Angular v5.0.0, you can use fromObject
from HttpParamOptions
to add multiple parameters at the same time.
const param = new HttpParams({fromObject: {aaa: '1', bbb: '222'}});
Also you can directly set parameters object
to methodsHttpClient
const obj = {aaa: '1', bbb: '222'};
this.http.get('test', { params: obj}).subscribe();
Refer to the demo , for the second method, please check the browser network to confirm that the parameters were added successfully.
source to share