Typescript http.get 错误:没有与此调用匹配的重载

Kat*_*rne 3 typescript angular

我试图从服务器获取一个文本文件,所以我这样做了:

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();
});
Run Code Online (Sandbox Code Playgroud)

它完全按照我想要的方式工作。然而编译器痛苦地喊道:

错误 TS2769:没有与此调用匹配的重载。重载 1 of 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?: 布尔值;}'。类型 '{ 标头中缺少属性 'observe':HttpHeaders; 响应类型:字符串;}' 但在类型 '{ headers?: HttpHeaders | 中是必需的 { [标题:字符串]:字符串 | 细绳[]; }; 观察:“事件”;参数?:HttpParams | { [参数:字符串]:字符串 | 细绳[]; }; 报告进度?:布尔值;响应类型?:“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

我在这里做错了什么?

Kat*_*rne 8

好了,所以修复是改变的responseType到'text' as 'json',则更换的返回类型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 => {
  ...
});
Run Code Online (Sandbox Code Playgroud)


Fel*_*lix 8

根据GitHub 的说法,应该通过以下方式修复:

接受 responseType:'text' 的 get 版本不是通用的,因为您已经声明响应将是一个字符串。

所以而不是:

return this.http.get<string>(this.url, {responseType: 'text'});
Run Code Online (Sandbox Code Playgroud)

只需使用非通用的:

return this.http.get(this.url, {responseType: 'text'});
Run Code Online (Sandbox Code Playgroud)

并参见此处的答案。


小智 5

您必须将 httpOptions 转换为 Object。我遇到了同样的问题,它对我来说非常有效。

 const httpOptions : Object = {
  headers: new HttpHeaders({
    'Accept': 'text/html',
    'Content-Type': 'text/plain; charset=utf-8'
  }),
  responseType: 'text'
};
Run Code Online (Sandbox Code Playgroud)

  • 铸造工程。谁能解释为什么我必须选择这些选项才能使其发挥作用? (2认同)