【问题标题】:Overload request headers and params with HttpClient get使用 HttpClient get 重载请求标头和参数
【发布时间】:2018-07-26 19:58:11
【问题描述】:

在 HttpClientModule 中,是否有传递 headers 和 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 获取发送请求标头和参数。

目前正在构建带有搜索参数和发送标头的完整 url。

【问题讨论】:

  • angular.io/api/common/http/HttpClient#get。您可以将所有这些作为选项对象的一部分传递。
  • 无法构建正确的语法,尝试获取 (url, options: { headers: headers, params: params});
  • This 可能对参数有所帮助。标题应该以类似的方式工作。 Headers 样品。

标签: angular http-get angular-http angular-http-interceptors angular-httpclient


【解决方案1】:

从 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

【讨论】:

    【解决方案2】:

    这是通过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;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      • 2016-06-24
      相关资源
      最近更新 更多