342

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.

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Miguel Lattuada
  • 5,327
  • 4
  • 31
  • 44
  • http://stackoverflow.com/questions/26541801/how-to-send-json-data-in-url-as-request-parameters-in-java refer this. Create URL before call and pass it to subscribe function in place of BASE_URL. 2cents – pratikpawar Dec 26 '15 at 21:51

11 Answers11

397

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.

Keithers
  • 354
  • 6
  • 23
toskv
  • 30,680
  • 7
  • 72
  • 74
  • yw, I'll add an example soon, or you can do it if you have it working already. :) – toskv Dec 26 '15 at 22:15
  • 2
    A gist: https://gist.github.com/MiguelLattuada/bb502d84854ad9fc26e0 how to use URLSearchParams object, thanks again @toskv – Miguel Lattuada Dec 26 '15 at 22:24
  • 1
    Super slick with the URLSearchParams! Solved my issue with serializing JSON object. – Logan H Sep 16 '16 at 21:37
  • There is no need for the variables, just use string interpolation with { search: ``var1=${val1}&var2=${val2}`` } – SlimSim Oct 31 '16 at 03:12
  • Does that mean, if I already have a link containing parameters (string), I have to cut it into pieces and rebuild it as the second method parameter? – Stefan Nov 18 '16 at 14:45
  • @Stefan no, it should work just fine if you use i as the url. – toskv Nov 18 '16 at 15:11
  • can o pass the whole object? i don't want to mess with each param in my service – Toolkit Dec 06 '16 at 14:12
  • 1
    @Toolkit looking at the api it is you can't give an object. If type safety is not a priority it might be that something like SilmSlim proposed might suit you better. – toskv Dec 06 '16 at 14:43
  • @Toolkit it should also be fairly easy to itterate over an object's keys and have them set in the params object. – toskv Dec 06 '16 at 14:59
  • @toskv. i too had similar kind of issue but mine is quite different. your ans helped me getting url binding with params. finally i need to build an url to call my rest api server using this url ( http://testsite.com/category/page/:pageId/:activeFilter ) i tried a lot. but it is not coming as i expected, this is what i am getting /category/page/?pageId=0&activeFilter=1 in my server console. i want to send only numerical number like `/category/page/0/1` any suggestions please – Sukumar MS May 19 '17 at 09:33
  • 2
    @SukumarMS there's really no need for anything special since it's part of the path. Just concatenate the strings 'blabla.com/page/' + page +'/activeFilter' + activeFilter. Or if you want to use template literals \`blabla.com/page/${page}/${activeFilter}\`. – toskv May 19 '17 at 10:50
  • @toskv is there any way to iterate the params in the class URLSearchParams once they are set? – ocespedes Jun 06 '17 at 20:17
  • @ocespedes check the documentation, there's a paramsMap property on the UrlSearchParams class. – toskv Jun 06 '17 at 20:54
  • 12
    this works for me: `http.get(url, {params: {var1: val1, var2: val2}})` – Alexander Suvorov Jul 06 '17 at 13:45
  • 9
    `search` property has been depricated from 4.0.0 -> use `params` instead – BotanMan Jul 10 '17 at 09:34
  • you are right, I'll update the answer with the 4.0.0 way of doing it – toskv Jul 10 '17 at 10:08
  • I am wondering if this query params are best handled in the component or in the service? – Winnemucca Oct 09 '17 at 17:43
  • @Winnemucca that depends on your application. It works anywhere. – toskv Oct 10 '17 at 07:14
  • 1
    Just as a side note URLSearchParams is deprecated – Musa Haidari Feb 06 '18 at 07:51
  • 1
    @Musa you are right, I'll add a comment saying that. – toskv Feb 06 '18 at 08:22
205

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())
...
Community
  • 1
  • 1
Radouane ROUFID
  • 10,595
  • 9
  • 42
  • 80
  • 3
    Not working for me. I digged into the source code and found that the second parameter of http.get expects a RequestOptionsArgs interface, which URLSearchParams does not implement. Wrapping the searchParams inside a RequestOptions object works. Would be nice to have a shortcut though. – hardsetting Feb 23 '17 at 13:57
  • 3
    You are totally right, I forgot `RequestOptions`. I updated my answer. – Radouane ROUFID Feb 23 '17 at 15:11
  • 1
    Thanks for pointing out deprecation of `search`. Fixed my prob – Hayden Braxton May 21 '17 at 21:49
  • Thank you for pointing this change out! All docs and issues I've found for hours have been telling me to attach params to `search` property. – rayepps Jul 11 '17 at 21:57
83

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

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
Rahmathullah M
  • 2,676
  • 2
  • 27
  • 44
18

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);
})
Stefan Mitic
  • 1,551
  • 1
  • 8
  • 8
9

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
ethemsulan
  • 2,241
  • 27
  • 19
8

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);
}
Kapil Raghuwanshi
  • 867
  • 1
  • 13
  • 22
  • 4
    This won't work if any of `searchParams`' properties are not `string` values. – Yulian Oct 16 '19 at 13:22
  • Correct, doesn't work on angular 13: Severity Code Description Project File Line Suppression State Error TS2769 (TS) No overload matches this call. Overload 1 of 15, '(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<...>', gave the following error. Argument of type '{ headers: { 'Content-Type': string; }; params: { isReset: boolean; }; }' is not assignable to paramet... – Ronen Festinger Mar 27 '22 at 21:55
5

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
      });
    });
});
mjwrazor
  • 1,866
  • 2
  • 26
  • 42
3

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

Cristhian D
  • 572
  • 6
  • 5
0
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

Fabio Antunes
  • 22,251
  • 15
  • 81
  • 96
Toolkit
  • 10,779
  • 8
  • 59
  • 68
0
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);
pushkin
  • 9,575
  • 15
  • 51
  • 95
vbrgr
  • 779
  • 7
  • 10
0

You can use Url Parameters from the official documentation.

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

Muhammed Ozdogan
  • 5,341
  • 8
  • 32
  • 53