305
votes

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.

11
stackoverflow.com/questions/26541801/… refer this. Create URL before call and pass it to subscribe function in place of BASE_URL. 2centspratikpawar

11 Answers

372
votes

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.

import {HttpClientModule} from '@angular/common/http';

@NgModule({
  imports: [ BrowserModule, HttpClientModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

After that you can inject the HttpClient and use it to do the request.

import {HttpClient} from '@angular/common/http'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  `,
})
export class App {
  name:string;
  constructor(private httpClient: HttpClient) {
    this.httpClient.get('/url', {
      params: {
        appid: 'id1234',
        cnt: '5'
      },
      observe: 'response'
    })
    .toPromise()
    .then(response => {
      console.log(response);
    })
    .catch(console.log);
  }
}

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:

 // 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
 }).subscribe(
   (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 and an working example here.

190
votes

Edit Angular >= 4.3.x

HttpClient has been introduced along with HttpParams. Below an example of use :

import { HttpParams, HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

let params = new HttpParams();
params = params.append('var1', val1);
params = params.append('var2', val2);

this.http.get(StaticSettings.BASE_URL, {params: params}).subscribe(...);

(Old answers)

Edit Angular >= 4.x

requestOptions.search has been deprecated. Use requestOptions.params instead :

let requestOptions = new RequestOptions();
requestOptions.params = params;

Original answer (Angular 2)

You need to import URLSearchParams as below

import { Http, RequestOptions, URLSearchParams } from '@angular/http';

And then build your parameters and make the http request as the following :

let params: URLSearchParams = new URLSearchParams();
params.set('var1', val1);
params.set('var2', val2);

let requestOptions = new RequestOptions();
requestOptions.search = params;

this.http.get(StaticSettings.BASE_URL, requestOptions)
    .toPromise()
    .then(response => response.json())
...
70
votes

Version 5+

With Angular 5 and up, you DON'T have to use HttpParams. You can directly send your json object as shown below.

let data = {limit: "2"};
this.httpClient.get<any>(apiUrl, {params: data});

Please note that data values should be string, ie; { params: {limit: "2"}}

Version 4.3.x+

Use HttpParams, HttpClient from @angular/common/http

import { HttpParams, HttpClient } from '@angular/common/http';
...
constructor(private httpClient: HttpClient) { ... }
...
let params = new HttpParams();
params = params.append("page", 1);
....
this.httpClient.get<any>(apiUrl, {params: params});

Also, try stringifying your nested object using JSON.stringify().

15
votes

Angular 6

You can pass in parameters needed for get call by using params:

this.httpClient.get<any>(url, { params: x });

where x = { property: "123" }.

As for the api function that logs "123":

router.get('/example', (req, res) => {
    console.log(req.query.property);
})
9
votes

My example

private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});

My method

  getUserByName(name: string): Observable<MyObject[]> {
    //set request params
    let params: URLSearchParams = new URLSearchParams();
    params.set("name", name);
    //params.set("surname", surname); for more params
    this.options.search = params;

    let url = "http://localhost:8080/test/user/";
    console.log("url: ", url);

    return this.http.get(url, this.options)
      .map((resp: Response) => resp.json() as MyObject[])
      .catch(this.handleError);
  }

  private handleError(err) {
    console.log(err);
    return Observable.throw(err || 'Server error');
  }

in my component

  userList: User[] = [];
  this.userService.getUserByName(this.userName).subscribe(users => {
      this.userList = users;
    });

By postman

http://localhost:8080/test/user/?name=Ethem
7
votes

In latest Angular 7/8, you can use the simplest approach:-

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

getDetails(searchParams) {
    const httpOptions = {
        headers: { 'Content-Type': 'application/json' },
        params: { ...searchParams}
    };
    return this.http.get(this.Url, httpOptions);
}
5
votes

If you plan on sending more than one parameter.

Component

private options = {
  sort:   '-id',
  select: null,
  limit:  1000,
  skip:   0,
  from:   null,
  to:     null
};

constructor(private service: Service) { }

ngOnInit() {
  this.service.getAllItems(this.options)
    .subscribe((item: Item[]) => {
      this.item = item;
    });
}

Service

private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});
constructor(private http: Http) { }

getAllItems(query: any) {
  let params: URLSearchParams = new URLSearchParams();
  for(let key in query){
    params.set(key.toString(), query[key]);
  }
  this.options.search = params;
  this.header = this.headers();

And continue with your http request just how @ethemsulan did.

Server side route

router.get('/api/items', (req, res) => {
  let q = {};
  let skip = req.query.skip;
  let limit = req.query.limit;
  let sort  = req.query.sort;
  q.from = req.query.from;
  q.to = req.query.to;

  Items.find(q)
    .skip(skip)
    .limit(limit)
    .sort(sort)
    .exec((err, items) => {
      if(err) {
        return res.status(500).json({
          title: "An error occurred",
          error: err
        });
      }
      res.status(200).json({
        message: "Success",
        obj:  items
      });
    });
});
2
votes

You can use HttpParams from @angular/common/http and pass a string with the query. For example:

import { HttpClient, HttpParams } from '@angular/common/http';
const query = 'key=value' // date=2020-03-06

const options = {
  params: new HttpParams({
    fromString: query
  })
}

Now in your code

this.http.get(urlFull, options);

And this works for you :)

I hoppe help you

0
votes
import ...
declare var $:any;
...
getSomeEndPoint(params:any): Observable<any[]> {
    var qStr = $.param(params); //<---YOUR GUY
    return this._http.get(this._adUrl+"?"+qStr)
      .map((response: Response) => <any[]> response.json())
      .catch(this.handleError);
}

provided that you have installed jQuery, I do npm i jquery --save and include in apps.scripts in angular-cli.json

0
votes
import { Http, Response } from '@angular/http';
constructor(private _http: Http, private router: Router) {
}

return this._http.get('http://url/login/' + email + '/' + password)
       .map((res: Response) => {
           return res.json();
        }).catch(this._handleError);
0
votes

You can use Url Parameters from the official documentation.

Example: this.httpClient.get(this.API, { params: new HttpParams().set('noCover', noCover) })