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

问题描述 投票:2回答:2

在HttpClientModule中,是否有一种方法可以传递header和params来获取请求。

   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获取发送请求头和参数。

目前正在构建包含搜索参数并发送标题的完整网址。

angular http-get angular-http angular-http-interceptors angular-httpclient
2个回答
6
投票

这是使用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;
});

0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.