HttpClient.get没有重载匹配此调用

时间:2020-03-18 09:58:37

标签: angular typescript

我希望能够下载文件(此处使用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>>;

我看不到我在做什么错。你能帮我吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您正在使用该函数的通用版本,但查看的是非通用文档。没有接受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