我为我的http调用创建标题,如下所示:
private createHeaders(headers: Map<string, string>): HttpHeaders {
let httpHeaders: HttpHeaders = new HttpHeaders();
for (const entry of Array.from(headers.entries())) {
httpHeaders = httpHeaders.append(entry[0], entry[1]);
}
return httpHeaders;
}
我设置标题,如下所示:
createOptions(headers: HttpHeaders) {
const options = {
headers: headers,
}
return options;
}
最后,我正在进行我的http GET调用:
get<T>(url: string, noLoadingIndicator?: boolean): Observable<T> {
return this.http.get<T>(url, this.createOptions(this.createHeaders(
new Map([['Content-Type', 'application/json'], ['showLoading', noLoadingIndicator ? 'off' : 'on']]
)
)));
}
这很有效。现在我需要获取文件,所以我这样做了:
getFile(url: string): Observable<Blob> {
return this.http.get(url, this.createOptionsBlob(
this.createHeaders(new Map([[ShowLoading, 'on']]
)
)));
}
createOptionsBlob(headers: HttpHeaders) {
const options = {
headers: headers,
responseType: 'blob' as 'blob' // Found this online, not sure how/why this works
}
return options;
}
如您所见,我必须创建一个单独的方法来创建包含responseType 的选项。
我尝试扩展createOptions以使其可配置为:
createOptions(headers: HttpHeaders, responseType?: string) {
const options = {
headers: headers,
responseType: responseType
}
return options;
}
但是我在get方法上遇到以下错误:
[TS] 类型&#39; {header:HttpHeaders; responseType:string; }&#39;不能分配给&#39; {headers?:HttpHeaders |类型的参数{[header:string]:string |串[]; };观察?:&#34;身体&#34 ;; params?:Ht ......&#39;。 财产的类型&#39; responseType&#39;是不相容的。 输入&#39; string&#39;不能分配给&#39;&#34; json&#34;&#39;。
如何让createOptions像我想的那样工作? HttpClient文档对我没有帮助。我错过了什么?