Miguel Lattuada Miguel Lattuada - 1 year ago 881
AngularJS Question

How to pass url arguments (query string) to a HTTP request on Angular 2

Hi guys I'm creating a HTTP request on Angular 2, but I do not know how to add url arguments (query string) to it.

(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.

Answer Source

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:

 // Parameters obj-
 let params: URLSearchParams = new URLSearchParams();
 params.set('appid', StaticSettings.API_KEY);
 params.set('cnt', days.toString());

 //Http request-
 return this.http.get(StaticSettings.BASE_URL, {
   search: params
   (response) => this.onGetForecastResult(response.json()), (error) => this.onGetForecastError(error.json()), () => this.onGetForecastComplete()

The documentation for the Http class has more details. It can be found here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download