angular - Typescript http.get 错误:没有重载匹配此调用
问题描述
我正在尝试从服务器获取文本文件,所以我这样做了:
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:没有重载匹配此调用。重载 1 的 15, '(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; 观察: "events"; params?: HttpParams | { [param: string ]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<...>',给出以下错误。'{ headers: HttpHeaders; 类型的参数 响应类型:字符串;}' 不能分配给类型为 '{ headers?: HttpHeaders | { [标题:字符串]:字符串 | 细绳[]; }; 观察:“事件”;参数?: HttpParams | { [参数:字符串]:字符串 | 细绳[]; }; 报告进度?:布尔值;响应类型?:“json”;withCredentials?:布尔值;}'。类型“{ 标头:”中缺少属性“观察”:HttpHeaders;响应类型:字符串;}' 但在类型 '{ headers?: HttpHeaders | { [标题:字符串]:字符串 | 细绳[]; }; 观察:“事件”;参数?: HttpParams | { [参数:字符串]:字符串 | 细绳[]; }; 报告进度?:布尔值;响应类型?:“json”;withCredentials?:布尔值;}'。
它列出了 15 个中的 3 个,他们都抱怨 responseType 应该是 'json' 但作为 responseType 的 'text' 绝对是重载之一:
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
我在这里做错了什么?
解决方案
好的,修复方法是将 responseType 更改为'text' as 'json'
,然后替换 to 的返回类型any
(string
这是确定要使用哪个重载的方式)。
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 => {
...
});
推荐阅读
- pug - 一种指纹/确定使用 Pug 作为模板引擎的网站的方法?
- python - Python:我可以在数组索引中使用 AND 运算符吗?
- javascript - 反应:即使在调用 setState 之后,重新渲染也会将状态设置为初始值
- python - 如果在 python 中出现警告,请执行某些操作
- python - 获取python中两个日期的天数差异
- angular - FormArray 和 AsyncValidators(不是 AsyncValicatorFn)
- react-native - Expo React-native Webview - 如何在 webview 中启动相同的外部 url?
- mpu6050 - 为稳定读数设置 mpu6050
- python - 使用 pandas DataFrame 从 1 开始索引(在 FIeld 下)
- apollo-client - Apollo Client,如何从获取所有元素的查询中获取一个元素