limit
limit

Reputation: 647

Angular 2 http get querystring params

Hopefully someone can help with this. I building an ionic 2 app which is based on the newer Angular 2, I am familiar with previous versions of Angular, but still trying to figure this whole typescript.

I have my API setup with basic get querystrings (e.g domain.com?state=ca&city=somename)

export class TestPage {
public state: string ='ca';
public city: string = null;
constructor(private http: Http){}

public submit() { 
   let url = "http://localhost/api"; 
   let payload = {"state": this.state, "city": this.city};
   this.$http.get(url, payload).subscribe(result => {
      //result
   }, err => {  
      //do something with the error 
   }
  )
 }
}

When I execute this it pulls my API url fine and I can get a response back, however none of the querystrings are being sent in the request. Its just sending http://localhost/api. If I console.log the payload its fine.

Ultimately I am trying to get it to do https://localhost/api?state=ca&city=example

Looking at examples I can't really find anything straight-forward on this.

Is it not possible to take a payload on http with this newer version of Angular? The code above is just an example. I have many querystrings, which is why I was hoping to send a payload to it.

Any help or suggestion would be appreciated.

Upvotes: 1

Views: 1151

Answers (1)

Shivam
Shivam

Reputation: 3131

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('state', this.state);
 params.set('city', this.city);

 //Http request-
 return this.http.get('http://localhost/api', {
   search: params
 }).subscribe(
   (response) => this.onGetForecastResult(response.json()), 
   (error) => this.onGetForecastError(error.json()), 
   () => this.onGetForecastComplete()
 );

Documentation: here

Upvotes: 1

Related Questions