首页 > 解决方案 > HttpClient.get 没有重载匹配这个调用

问题描述

我希望能够下载文件(这里使用 blob)。为此,我需要从嵌入在标题“content-disposition”中的服务器中检索文件名。这是我的功能:

const header = {Authorization: 'Bearer  ' + token};
const config = {headers: header, responseType: 'blob' as 'blob', observe: 'response' as 'response'};
return this.http.get<HttpResponse<Blob>>(url, config);

但我得到了错误:

error TS2345: Argument of type '{ headers: { Authorization: string; }; responseType: "blob"; observe: "response"; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'.
Types of property 'observe' are incompatible.
Type '"response"' is not assignable to type '"body"'.

当我转到函数定义时,我得到:

/**
 * Constructs a `GET` request that interprets the body as a `Blob` and
 * returns the full `HTTPResponse`.
 *
 * @param url     The endpoint URL.
 * @param options The HTTP options to send with the request.
 *
 * @return An `Observable` of the `HTTPResponse` for the request,
 *  with the response body as a `Blob`.
 */
get(url: string, options: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe: 'response';
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType: 'blob';
    withCredentials?: boolean;
}): Observable<HttpResponse<Blob>>;

我不明白我做错了什么。你能帮我吗 ?

谢谢你的帮助 !

标签: angulartypescript

解决方案


您正在使用该函数的通用版本,但正在查看非通用文档。没有接受的通用重载observe: 'response', responseType: 'blob'

相反,使用非通用版本:

const header = {Authorization: 'Bearer  ' + token};
const config = {headers: header, responseType: 'blob' as 'blob', observe: 'response' as 'response'};
return this.http.get(url, config);

所有的泛型重载只允许responseType: 'json'.

来源:https ://github.com/angular/angular/blob/master/packages/common/http/src/client.ts


推荐阅读