在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/