【问题标题】:PdfMake: function getBase64 return undefined valuePdfMake:函数getBase64返回未定义的值
【发布时间】:2018-04-19 15:39:54
【问题描述】:

我正在使用 PdfMake 生成一个 Pdf 文件,并使用 getBase46() 方法将其编码为 base64 字符串数组,如下所示:

 let base64: string;

 this.pdf.createPdf(buildPdf(pdfModel)).getBase64(
      function(encodedString) {
        base64 = encodedString;
        console.log(base64); // base64 is not undefined and is a some string
      }
 );

 console.log(base64); // base64 is undefined here

如何在function 之外获取变量base64

【问题讨论】:

    标签: javascript typescript callback promise pdfmake


    【解决方案1】:

    这是一个异步操作,你只能保证值会在回调函数内部定义。

    【讨论】:

    • 这意味着没有选项可以在回调之外获取字符串? @mcrvaz
    • 理想情况下,您应该使用 Promise,但无论哪种方式,字符串都只能在“then”中定义。您必须在该函数中执行您的操作。
    【解决方案2】:

    我终于通过将我的类的实际 context (this) 绑定到回调function 的上下文来解决它,这样 var base64 也可以设置在通话结束:

        let base64: string;
    
        this.pdf.createPdf(buildPdf(pdfModel)).getBase64(
            function(encodedString) {
               base64 = encodedString;
               console.log(this.base64); // this.base64 refers to var on the top
            }.bind(this) // To bind the callback with the actual context
        );
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多