Update: Angular 4 Http Request with Querry Params
Hello There,
It is about the changes in Angular APIs to handle request and response for HTTP calls.
Earlier in Angular 2 we used to call HTTP requests with the help of RequestOptions class, where we have to pass a new instance of URLSearchParams inside the constructor call of RequestOptions class.
Following are the example of an Angular2 HTTP request where we have to follow the following steps; if we need to pass any query parameter along with the GET request.
let headers = new Headers({
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’
});
let request_data = new URLSearchParams();
request_data.set(‘sample_param’, “Sample_Value”);
let request_option = new RequestOptions({ headers: this.headers, search: request_data});
this.http.get(“http://…..your_api_url…..", request_option)
.map(res => res.json());
In the above example, we are passing the object of the URLSearchParams class as value of search key of the object which is being passed to construct the RequestOptions’s instance.
Get Premchand Kumar’s stories in your inbox
Join Medium for free to get updates from this writer.
Since the new approach of angular4, there is an explicit property “params” has been defined on the RequestOption class to rest the query params dynamically. Hence the above example wont work and have to be re-written like following:
let headers = new Headers({
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’
});
let request_data = new URLSearchParams();
request_data.set(‘sample_param’, “Sample_value”);
let request_option = new RequestOptions({ headers: this.headers});
request_option.params = request_data;
this.http.get(“http://…..your_api_url…..", request_option)
.map(res => res.json());
there are some other key differences in angular2 and 4 in HTTP request which I would try to list down here in my next blog.
Stay tuned for more…
Reference:






