Hi guys I'm creating a HTTP request on Angular, but I do not know how to add url arguments (query string) to it.
this.http.get(StaticSettings.BASE_URL).subscribe(
(response) => this.onGetForecastResult(response.json()),
(error) => this.onGetForecastError(error.json()),
() => this.onGetForecastComplete()
);
Now my StaticSettings.BASE_URL is something like a url with no query string like: http://atsomeplace.com/ but I want it to be http://atsomeplace.com/?var1=val1&var2=val2
Where var1, and var2 fit on my Http request object? I want to add them like an object.
{
query: {
var1: val1,
var2: val2
}
}
and then just the Http module do the job to parse it into URL query string.
Angular 6
You can pass in parameters needed for get call by using params:
where x = { property: "123" }.
As for the api function that logs "123":
The HttpClient methods allow you to set the params in it's options.
You can configure it by importing the HttpClientModule from the @angular/common/http package.
After that you can inject the HttpClient and use it to do the request.
For angular versions prior to version 4 you can do the same using the Http service.
The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.
The search field of that object can be used to set a string or a URLSearchParams object.
An example:
The documentation for the Http class has more details. It can be found here and an working example here.
Version 5+
With Angular 5 and up, you DON'T have to use HttpParams. You can directly send your json object as shown below.
Please note that data values should be string, ie;
{ params: {limit: "2"}}
Version 4.3.x+
Use HttpParams, HttpClient from @angular/common/http
Might help some!
My example
My method
in my component
By postman
Edit Angular >= 4.3.x
HttpClient has been introduced along with HttpParams. Below an example of use :
(Old answers)
Edit Angular >= 4.x
requestOptions.search
has been deprecated. UserequestOptions.params
instead :Original answer (Angular 2)
You need to import
URLSearchParams
as belowAnd then build your parameters and make the http request as the following :
If you plan on sending more than one parameter.
Component
Service
And continue with your http request just how @ethemsulan did.
Server side route