使用 HttpClient get 重载请求标头和参数 [英] Overload request headers and params with HttpClient get

查看:35
本文介绍了使用 HttpClient get 重载请求标头和参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在HttpClientModule中,是否有一种方法可以通过headers和params来获取请求.

In HttpClientModule, is there a method to pass headers and params to get request.

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

I want something like requestoptions to hold both or a syntax to do httpClient get sending request headers and params.

目前正在使用搜索参数构建完整的 url 并发送标头.

Currently building complete url with search params and sending headers along.

推荐答案

这里是通过 get 传递标头和参数的东西,它使用 HttpParamsOptions将一个对象序列化为HttpClient可以处理的参数.

Here is something that passes both headers and parameters in with a get, and it uses HttpParamsOptions to serialize an object into parameters that the HttpClient can cope with.

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

这篇关于使用 HttpClient get 重载请求标头和参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆