I would like to trigger HTTP request from an Angular component, 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 like a URL without query string like: http://atsomeplace.com/
but I want it to be like http://atsomeplace.com/?var1=val1&var2=val2
How to add var1
, and var2
to my HTTP request object as an object?
{
query: {
var1: val1,
var2: val2
}
}
and then just the HTTP module does the job to parse it into URL query string.
Best Answer
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.