使用 HttpClient get 重载请求 headers 和参数

Overload request headers and params with HttpClient get

在HttpClientModule中,有没有通过headers和参数获取请求的方法。

   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 

我想要像 requestoptions 这样的东西来保存两者,或者想要一个语法来做 httpClient 获取发送请求 headers 和参数。

目前正在使用搜索参数构建完整 url 并发送 headers。

这里是通过 get 传递 headers 和参数的东西,它使用 HttpParamsOptions 将 object 序列化为 HttpClient 可以处理的参数与.

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

从 Angular 5.0.0-beta.6 (2017-09-03) 开始,您现在可以使用以下语法传入 headers 和参数:

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

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

来源:https://github.com/angular/angular/pull/18490