<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();
}
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)
错误消息中的原因很明显
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' }