Angular (5) httpclient 观察和 responseType: 'blob'

新手上路,请多包涵

上下文:我正在尝试从后端下载二进制文件(这需要一些作为 json-body 发布的数据),并使用后端在 content-disposition 标头中指定的文件名将其保存在文件保护程序中。要访问标题,我认为我需要 HttpResponse。

但我无法将 angular 的 HttpClient.post<T>(...): Observable<HttpResponse<T>>; 方法与 Blob 一起使用。

当我打电话

this.httpclient.post<Blob>('MyBackendUrl',
        params,
        {observe: 'response', responseType: 'blob'});
the compiler complains about the 'blob' ('json' is accepted by the compiler):

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

当我将选项放在自己的对象中时,如 https://stackoverflow.com/a/48016652/2131459 所示(但没有“as”…) post(…):Observable 被调用,我不能访问标题。

顺便说一句,即使是简单的示例 return this.http.get<Blob>('backendUrl', {responseType: 'blob'});https://stackoverflow.com/a/46882407/2131459 中所见,对我也不起作用。

使用的版本

  • Angular 版本:5.0.3(将在一周左右更新到最新的 5 个)
  • 打字稿:2.4.2
  • 网络包:3.8.1

原文由 Chris 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 978
1 个回答

使用 observe:response 时,不要键入调用( post<Blob>(...) ),因为返回的 Observable 将是 HttpResponse。所以这应该工作:

 this.httpclient.post('MyBackendUrl',
    params,
    {observe: 'response', responseType: 'blob'}
);

为什么会发生这种情况,是否有两个版本的 post 方法,一个具有泛型类型,一个没有:

 /**
     * Construct a POST request which interprets the body as JSON and returns the full event stream.
     *
     * @return an `Observable` of all `HttpEvent`s for the request, with a body type of `T`.
     */
    post<T>(url: string, body: any | null, options: {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe: 'events';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType?: 'json';
        withCredentials?: boolean;
    }): Observable<HttpEvent<T>>;
    /**
     * Construct a POST request which interprets the body as an `ArrayBuffer` and returns the full response.
     *
     * @return an `Observable` of the `HttpResponse` for the request, with a body type of `ArrayBuffer`.
     */
    post(url: string, body: any | null, options: {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe: 'response';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType: 'arraybuffer';
        withCredentials?: boolean;
    }): Observable<HttpResponse<ArrayBuffer>>;

原文由 funkizer 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进