You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Ionic处理二进制/XLSX响应报错:类型不匹配问题

问题:Angular Ionic下载Excel模板时的类型不匹配错误

在Angular Ionic项目中实现二进制/XLSX文件下载功能时,get请求返回类型与预期不匹配,出现编译错误。

报错信息

Type 'Observable<HttpEvent<Blob>>' is not assignable to type 'Observable<Blob>'.
Type 'HttpEvent<Blob>' is not assignable to type 'Blob'.
Type 'HttpSentEvent' is missing the following properties from type 'Blob': size, arrayBuffer, bytes, slice, and 2 more.ts(2322)

相关代码

HTML文件

<ion-button color="primary" expand="block" (click)="downloadPredefinedExcel()" [disabled]="downloadedExcel">
    <ion-icon name="download-outline" slot="start"></ion-icon>
    Download Excel Template
</ion-button>

组件Typescript文件

// Download the excel file for bulk upload data
downloadPredefinedExcel() {
  this.commonService.present();
  this.productService.getDownloadExcelForBulkUpload().pipe(
    tap((blob: Blob) => {
      this.commonService.dismiss();
      this.downloadedExcel = true;
      this.downloadFile(blob, 'BulkUploadTemplate.xlsx'); // Change the filename if needed
      this.commonService.success('Download Successfully');
    }),
    catchError((error) => {
      this.commonService.dismiss();
      this.commonService.danger('Download failed.');
      return throwError(() => new Error(error.message));
    })
  ).subscribe();
}

downloadFile(blob: Blob, filename: string) {
  const link = document.createElement('a');
  const url = window.URL.createObjectURL(blob);
  link.href = url;
  link.download = filename;
  link.click();
  window.URL.revokeObjectURL(url);
}

Service文件

/* For Download Excel Bulk Upload */
getDownloadExcelForBulkUpload() {
  return this.commonApi.getDownloadExcelForBulkUpload();
}

Common API文件

getDownloadExcelForBulkUpload() {
  return this.getBlob(`${environment.baseUrl + ApiUrls.DownloadExcelForBulkUpload}`);
}

GenericApi API文件

protected getBlob(url: string, options: any = {}): Observable<Blob> {
  return this.http.get<Blob>(url, { ...options });
}

ApiUrls文件

DownloadExcelForBulkUpload: '/api/files/bulkUpload/ServiceDownload',

解决方案

错误根源是HttpClient的get请求未明确指定responseType: 'blob',导致Angular默认返回HttpEvent<Blob>类型的Observable(包含请求生命周期事件),而非直接返回Blob对象。

修改GenericApi中的getBlob方法,添加responseType: 'blob'选项:

protected getBlob(url: string, options: any = {}): Observable<Blob> {
  return this.http.get(url, {
    ...options,
    responseType: 'blob'
  });
}

说明

当指定responseType: 'blob'后,Angular会将响应直接解析为Blob对象,返回的Observable类型即为Observable<Blob>,与代码中预期的类型匹配,编译错误即可解决。

内容的提问来源于stack exchange,提问作者keshav godani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 14:29:55