使用HttpClient重载请求标头和参数

Rk *_*iri 2 http-get angular-http angular-http-interceptors angular angular-httpclient

在HttpClientModule中,是否有一种传递标头和参数来获取请求的方法。

   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 
Run Code Online (Sandbox Code Playgroud)

我想要类似requestoptions的内容,或者想要一种语法来使httpClient获得发送请求标头和参数。

当前使用搜索参数构建完整的url并发送标头。

R. *_*rds 7

这是通过传递标题和参数的东西,get它用于HttpParamsOptions将对象序列化为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;
});
Run Code Online (Sandbox Code Playgroud)


Kev*_*ven 5

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

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

this.http.get('http://www.example.org', httpOptions);
Run Code Online (Sandbox Code Playgroud)

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