首页 > 解决方案 > 在 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。

标签: angulardownloadpdf-generationangular-promisebytestream

解决方案


你可以这样尝试

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();
}

推荐阅读