上下文:我正在尝试从后端下载二进制文件(这需要一些作为 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 许可协议
使用
observe:response
时,不要键入调用(post<Blob>(...)
),因为返回的 Observable 将是 HttpResponse。所以这应该工作:为什么会发生这种情况,是否有两个版本的 post 方法,一个具有泛型类型,一个没有: