在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获取发送请求标题和参数。
目前正在构建包含搜索参数并发送标题的完整网址。
答案 0 :(得分: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;
});
答案 1 :(得分: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);