如何处理二进制文件或XLSX作为响应?

问题描述 投票:0回答:1
如何处理二进制文件或XLSX作为Angular Ionic的响应。我已经这样做了,但是当我返回获取方法时,我会遇到错误。

enter image description here 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); }

服务文件:

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

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

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

apiurls文件:
DownloadExcelForBulkUpload: '/api/files/bulkUpload/ServiceDownload',

但是我在通用API文件上遇到此错误:
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)

错误消息中的原因很明显
angular typescript ionic-framework rxjs blob
1个回答
0
投票

HttpClient.get

默认情况下返回Observable

。 您可以按照以下方式键入:

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

as json
用于打字稿类型检查


to对象破坏the键的丢失,只需使用typescript的typecript重新键入,如下所示。

{ ...options, responseType: 'blob' }

    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.