我正在尝试从服务器获取文本文件,所以我做到了:
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'text/html',
'Content-Type': 'text/plain; charset=utf-8'
}),
responseType: 'text'
};
this.http.get<any>(url, httpOptions).subscribe(response => {
const blob = new Blob([response], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.download = 'user-permission-auditlog' + endDate.toUTCString() + '.csv';
anchor.href = url;
anchor.click();
});
它完全按照我想要的方式工作。但是,编译器痛苦不已:
错误TS2769:没有过载与该调用匹配。 重载15之1,'((URL:字符串,选项:{标头?:HttpHeaders | {[header:string]:字符串| string [];};观察:“ events”; params ?: HttpParams | {[param:string ]:string | string [];}; reportProgress ?: boolean; responseType ?:“ json”; withCredentials ?: boolean;}):Observable <...>',出现以下错误。 类型'{标题的参数:HttpHeaders; responseType:字符串; }'不可分配给类型'{headers ?: HttpHeaders | {[header:string]:字符串|串[]; };观察:“事件”;参数:HttpParams | {[参数:字符串]:字符串|串[]; }; reportProgress ?:布尔值; responseType ?:“ json”; withCredentials ?:布尔值; }'。 类型'{headers:HttpHeaders;中缺少属性'observe'。 responseType:字符串; }”,但类型为“ {headers?:HttpHeaders | {[header:string]:字符串|串[]; };观察:“事件”;参数:HttpParams | {[参数:字符串]:字符串|串[]; }; reportProgress ?:布尔值; responseType ?:“ json”; withCredentials ?:布尔值; }'。
它列出了15个中的3个,他们所有人都抱怨responseType应该是'json',但是'text'作为responseType绝对是重载之一:
get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<string>
https://angular.io/api/common/http/HttpClient#get
我在做什么错了?
答案 0 :(得分:4)
好的,解决方法是将responseType更改为'text' as 'json'
,然后将返回类型any
替换为string
(这是确定要使用的重载的方式)。 / p>
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'text/html',
'Content-Type': 'text/plain; charset=utf-8'
}),
responseType: 'text' as 'json'
};
this.http.get<string>(url, httpOptions).subscribe(response => {
...
});
答案 1 :(得分:2)
您必须将httpOptions强制转换为Object。我遇到了同样的问题,对我来说效果很好。
const httpOptions : Object = {
headers: new HttpHeaders({
'Accept': 'text/html',
'Content-Type': 'text/plain; charset=utf-8'
}),
responseType: 'text'
};
答案 2 :(得分:0)