I'm trying to generate a PDF file from an endpoint, the showPDF function has an ID parameter of the Product and generate a PDF as an output.
I've tried to declare a Promise to get the bytes stream from that endpoint:
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();
}
The issue is that the downloadlink is executed before getting the result from the Promise.
For instance, when calling showPDF(942) I get an undefined value of the download link
When calling showPDF for the same ID or another ID value, it generates the PDF but from the previous bytes stream value got from the Promise.