Overload request headers and params with HttpClient get

可紊 提交于 2019-12-10 11:04:08

问题


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.


回答1:


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;
});



回答2:


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



来源:https://stackoverflow.com/questions/48817781/overload-request-headers-and-params-with-httpclient-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!