10

In HttpClientModule, is there a method to pass headers and params to get request.

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

   const headers = { headers: new HttpHeaders({}) }
   let params = new HttpParams({ });
   get(url, {params}) // http client get with params
   get(url, {headers}); //http client get with headers 

I want something like requestoptions to hold both or a syntax to do httpClient get sending request headers and params.

Currently building complete url with search params and sending headers along.

Rk R Bairi
  • 1,289
  • 7
  • 15
  • 39
  • 1
    https://angular.io/api/common/http/HttpClient#get. You can pass all of that in as a part of an options object. – R. Richards Feb 15 '18 at 23:16
  • unable to build right syntax , tried get (url, options: { headers: headers, params: params}); – Rk R Bairi Feb 15 '18 at 23:40
  • [This](https://stackoverflow.com/questions/48723355/angular-5-is-there-anything-like-httpparamserailizer-that-was-available-in-ang/48723902#48723902) might help for the params. The headers should work in a similar fashion. [Headers](https://angular.io/guide/http#adding-headers) sample. – R. Richards Feb 15 '18 at 23:51

2 Answers2

17

Here is something that passes both headers and parameters in with a get, and it uses HttpParamsOptions to serialize an object into parameters that the HttpClient can cope with.

localvar: any;

const headers = new HttpHeaders().set('Content-Type', 'application/json');

const myObject: any = { this: 'thisThing', that: 'thatThing', other: 'otherThing'};
const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;

const options = { params: new HttpParams(httpParams), headers: headers };

this.httpClient.get<any>('https://server:port/api/endpoint', options)
  .subscribe((data: any) => {
      this.localvar = data;
});
R. Richards
  • 24,603
  • 10
  • 64
  • 64
6

As of Angular 5.0.0-beta.6 (2017-09-03), you can now pass in both headers and parameters using the below syntax:

const httpOptions = {
  headers: { 'Content-Type': 'application/json' },
  params: {'include': 'somethingCool'}
};

this.http.get('http://www.example.org', httpOptions);

Source: https://github.com/angular/angular/pull/18490

neuquen
  • 3,991
  • 15
  • 58
  • 78