angular - 在 Angular 中获取字节流时,下载链接未定义
问题描述
我正在尝试从端点生成 PDF 文件,showPDF 函数具有产品的 ID 参数并生成 PDF 作为输出。
我试图声明一个 Promise 以从该端点获取字节流:
showPdf(rowData: Product) {
console.log("ID = >" + rowData.id);
let promise = new Promise((resolve, reject) => {
let apiURL = this.apiUrl + "/api/products/get/pdf/"+rowData.id;
this.http.get(apiURL)
.toPromise()
.then(
res => { // Success
this.results = String(res);
console.log("Bytes=> " + res);
resolve();
},
msg => { // Error
reject(msg);
}
);
});
const bytes = this.results;
const linkSource = 'data:application/pdf;base64,'+ bytes;
const downloadLink = document.createElement("a");
const fileName = "Report.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
console.log("downloadLink = >" + downloadLink);
downloadLink.click();
}
问题是下载链接是在从 Promise 获取结果之前执行的。
例如,当调用 showPDF(942) 我得到一个未定义的下载链接值
当为相同的 ID 或另一个 ID 值调用 showPDF 时,它会生成 PDF,但会根据从 Promise 获得的先前字节流值生成 PDF。
解决方案
你可以这样尝试
showPdf(rowData: Product) {
console.log("ID = >" + rowData.id);
let promise = new Promise((resolve, reject) => {
let apiURL = this.apiUrl + "/api/products/get/pdf/"+rowData.id;
this.http.get(apiURL)
.toPromise()
.then(
res => { // Success
this.results = String(res);
console.log("Bytes=> " + res);
// here after getting the result we are calling the another function to download the PDF
this.downLoadPdf();
resolve();
},
msg => { // Error
reject(msg);
}
);
});
}
downLoadPdf() {
const bytes = this.results;
const linkSource = 'data:application/pdf;base64,'+ bytes;
const downloadLink = document.createElement("a");
const fileName = "Report.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
console.log("downloadLink = >" + downloadLink);
downloadLink.click();
}
推荐阅读
- node.js - Mongodb 节点驱动程序 - 当我调用 db.close() 时真的很重要还是我很幸运?
- java - Kafka 流不会以聚合值重新启动
- javascript - React Native - 搜索过滤器
- amazon-web-services - AWS CodePipeline - 删除 Github Webhook
- go - 长时间运行的 cgo 函数调用超时
- ios - 从 UITableViewCell 传递数据
- python - Python-snappy:如何将多个压缩的 snappy 文件合并为一个?
- opencart - 在 opencart 3.0.2.0 图像管理器中按日期对图像进行排序
- ruby-on-rails - Ruby Rails 5.1.6 测试在唯一列上失败
- python - Python cprofile 文件名:lineno 获取完整路径