Reputation: 8652
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?
Upvotes: 4
Views: 5328
Reputation: 121
HttpParams
is immutable. set()
creates and returns a new HttpParams
instance, without mutating the instance on which set()
is called. So the code should be
const params = new HttpParams().set('status', status);
Upvotes: 0
Reputation: 38171
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');
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.
Upvotes: 18