[英]Open pdf file in new tab in Angular
我正在尝试在 Angular 9 的新选项卡中实现 pdf 文件打开。我从 api 接收文件作为 blob。 但是由于window.URL.createObjectURL(blob);
已弃用我得到这个Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
错误。 我看到现在我应该使用MediaStream()
进行他的操作,但我不知道如何使它与 blob 一起工作。
我的代码现在看起来像这样,但它缺少主要部分:
downloadFile() {
console.log('File download started.');
const blob = this.agreementService.getPdfReport(this.agreementNumber);
// Deprecated part
const url = window.URL.createObjectURL(blob);
const link = this.downloadZipLink.nativeElement;
link.href = url;
link.download = 'Agreement.pdf';
link.click();
window.URL.revokeObjectURL(url);
}
协议.service.ts:
getPdfReport(agreementNumber: string){
this.requestUrl = `${configs.api}v1/reports/${agreementNumber}/Agreement.pdf`;
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
return this.http.get(this.requestUrl, {headers, responseType: 'blob'});
}
从几个答案中提出了我自己的解决方案。 如果我做错了什么,请在评论中纠正我。
协议.service.ts:
getPdfReport(agreementNumber: string) {
this.requestUrl = `${configs.api}v1/reports/${agreementNumber}/Agreement.pdf`;
return this.http.get(this.requestUrl, { responseType: 'blob', observe: 'response'}).pipe(
map((res: any) => {
return new Blob([res.body], { type: 'application/pdf' });
})
);
}
协议.component.ts:
this.agreementService.getPdfReport(this.agreementNumber).subscribe(res => {
const fileURL = URL.createObjectURL(res);
window.open(fileURL, '_blank');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.