When using Angular 7, I encountered an issue while calling an API with the GET method and attempting to download a file using the 'saveAs' function from the fileSaver library.
After retrieving the filename from the response header, I found that I was unable to properly download the file. Instead, I received '[Object object]' in the file content. However, everything worked fine when using a dummy name.
This is my component file:
fileName:string="";
const MIME_TYPE ={
XLSX:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
TXT:'text/*',
PDF:'application/pdf'
}
downloadFile(){
this.DownloadService.downloadFile(
(data: any) => {
this.fileName=data.headers.get('fileName');
const EXT = this.fileName.substr(this.fileName.lastIndexOf('.')+1);
saveAs(new Blob([data],{type:MIME_TYPE[EXT]}),this.fileName);
}
);
}
Here is the DownloadService file:
public downloadFile(callback: (responseData: any) => void): void {
this.apiService.downloadFile.subscribe((data: any) => {
if (callback) {
callback(data);
}
});
}
And here is the apiService file:
downloadFile(param: any): Observable<any> {
return this.http.get(api/download, {responseType:'blob',observe: 'response' });
}
The output in the file content is:
[Object object]