Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload request headers and params with HttpClient get

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.

like image 646
Rk R Bairi Avatar asked Feb 15 '18 23:02

Rk R Bairi


1 Answers

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;
});
like image 73
R. Richards Avatar answered Sep 22 '22 07:09

R. Richards