I'm trying to download a PDF from an API using Angular.
Here's the service I've created to make the API call:
getPDF(id:any) {
return this.http.get(
`url?=${id}`,
{ responseType: 'blob' as 'json', observe: 'response' }
);
}
Within my component file, I'm using the service to trigger the PDF download.
onGeneratepdf() {
this.service
.getPDF(
123
)
.subscribe((res: any) => {
let filename = res.header
?.get('content-disposition')
?.split(';')[1]
.split('=')[1];
let blob: Blob = res.body as Blob;
var a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.click();
});
}
When I click onGeneratePDF, the PDF is downloaded but the issue is that it's saved as undefined.pdf instead of user.pdf. Additionally, the response headers show:
access-control-allow-origin: *
cache-control: no-cache, no-store, max-age=0, must-revalidate
content-disposition: attachment; filename=user.pdf
content-type: application/pdf
Any assistance with resolving these problems would be greatly appreciated.
Thanks in advance.