我试图下载在API响应中作为blob接收的XLSX文件,但它被接收为HttpErrorResponse
这是由于角度的请求结构从angular5的变化。
我尝试过请求,该请求以HttpErrorReponse对象响应,如下所示:
myBlobRequest():Observable<any>{
return this.http.get(url, { responseType: 'blob'})
.map((response: Response) => {
return response;
})
.catch((res: Response) => {
// handleError(response)
});
}
以下解决方案对我有用。因为它在HttpErrorResponse中给出了 json 解析错误
解决方案:
{ responseType: 'blob'} should be replaced with { responseType: 'blob' as 'json'}
请求:
获取方法 :
myBlobRequest():Observable<any>{
return this.http.get(url, { responseType: 'blob' as 'json' })
.map((response: Response) => {
return response;
})
.catch((res: Response) => {
// handleError(response)
});
}
响应:
订阅者函数中的句柄:
- 使用文件保护程序库:
this.serviceObj.myBlobRequest.subscribe((blobResponse)=>{
var blob = new Blob([resp], { type: 'application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet;' });
FileSaver.saveAs(blob, "test.xlsx");
});
- 没有文件保护程序库:
this.serviceObj.myBlobRequest.subscribe((blobResponse)=>{
var blob = new Blob([resp], { type: 'application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet;' });
// Download File without FileSaver
const downloadUrl = window.URL.createObjectURL(blob);
var link = document.createElement('a');
link.href = downloadUrl;
link.download = "test.xlsx";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});