I'm struggling to display or download a .pdf file in my Angular 7 project due to issues with window.URL.createObjectURL. Here's the code snippet I've written:
this.userService.getFile(report.id).subscribe(
res => {
console.log(res)
const filename = res.headers.get('content-disposition').split(';')[1].split('=')[1].replace(/\"/g, '')
const blob = new Blob([res.body], { type: res.body.type })
const url = window.URL.createObjectURL(blob)
const a: HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement
a.href = url
a.download = filename
window.document.body.appendChild(a)
a.click()
window.document.body.removeChild(a)
URL.revokeObjectURL(url)
},
err => {
console.log(err)
}
The function getFile() makes a simple HTTP request
getFile(fileId: string): Observable<any> {
return this.http.get(environment.API_URL + '/file/' + fileId, {observe: 'response', responseType: 'blob'})
}
My IDE is flagging an 'Instance member is not accessible' error with window.URL.createObjectURL()
The file seems to be successfully fetched from the server, and I see the 'Navigate to blob://' message in the console, but the download prompt doesn't appear.
I've used this same method in a previous Angular project (version 6) and it worked perfectly. I'm puzzled why it's not working now. Any advice?
Thank you!