I'm trying to migrate my Http
requests to HttpClient
requests.
I was able to migrate my post
queries but I'm facing a problem while migrating get
queries. When I do so, my backend doesn't receive any parameters respectively, it tells me that the parameters are not provided and 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?
Currently HttpParams
is immutable, you should set params as below:
// for set method
let params: HttpParams = new HttpParams().set('something', 'hello');
// for append method
let params: HttpParams = new HttpParams().append('something', 'hello');
HttpParams's set
and append
method will overwrite the original params
instance with the newly updated one by set
and append
, and finally return the new instance.
So we can do it in multiple lines as below:
let params: HttpParams = new HttpParams();
params = params.set('something', 'hello');
params = params.append('something2', 'hello2');
Plunker demo
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 set object
parameters to HttpClient
methods directly
const obj = {aaa: '1', bbb: '222'};
this.http.get('test', { params: obj}).subscribe();
Refer demo, for the second way, please check browser's network to confirm the parameters has been added successfully.
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