angular - 使用 HttpClient get 重载请求 header 和参数

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

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

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

当前正在使用搜索参数构建完整的网址并发送 header 。

最佳答案

这里使用 get 传递 header 和参数,并使用 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;
});

关于angular - 使用 HttpClient get 重载请求 header 和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48817781/

相关文章:

php - 如何在 URL 中传递 POST 参数?

html - 我可以在 Spring Boot 应用程序中从 Thymeleaf 表发出 HTTP POST 请求吗

angularjs - Angular $http.get 错误,意外 token

asynchronous - Angularjs bootstrap UI typeahead 无法异步工作

javascript - PrimeNG Autocomplete 不通过输入搜索查询显示任何建议

javascript - 将单独的按钮映射到单独的 CSS 文件以更改我页面的背景图像

angular - Bootstrap 后如何通过 APP_INITIALIZER 引用服务中设置的属性

javascript - 无法将 http 结果保存到范围

jquery - 从 jquery $.ajax 到 angular $http

css - 如何重叠 Angular Material 元素