[在Angular中获取字节流时,下载链接未定义

问题描述 投票:0回答:1

我正在尝试从端点生成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)时,我获得了下载链接的未定义值

enter image description here

当为相同的ID或另一个ID值调用showPDF时,它会生成PDF,但它是从Promise获得的先前字节流值中产生的。

angular pdf-generation angular-promise downloadfile bytestream
1个回答
0
投票

您可以尝试这样

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();
}
© www.soinside.com 2019 - 2024. All rights reserved.