首页 > 解决方案 > 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

我在这里做错了什么?

标签: angulartypescript

解决方案


好的,修复方法是将 responseType 更改为'text' as 'json',然后替换 to 的返回类型anystring这是确定要使用哪个重载的方式)。

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 => {
  ...
});

推荐阅读