1

I am generating a Pdf-file with PdfMake and encode this in base64 string array with the method getBase46() like this:

 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

How can I get the variable base64 outside the function?

Manu
  • 1,065
  • 14
  • 21

2 Answers2

3

I finally solved it by binding the actual context (this) of my Class to the context of the callback function, so that the var base64 can also be set at the end of the call:

    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
    );
Manu
  • 1,065
  • 14
  • 21
  • can also see here for other explanations: ( https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) and the official doc of Typescript: (https://www.typescriptlang.org/docs/handbook/functions.html) – Manu Nov 08 '17 at 13:45
1

This is an asynchronous operation, you can only guarantee that the value will be defined inside the callback function.

mcrvaz
  • 662
  • 3
  • 8
  • It means there is no option to get the string outside the callback ? @mcrvaz – Manu Nov 07 '17 at 11:03
  • Ideally you should be using promises, but either way the string would only be defined inside the "then". You must execute your operations inside that function. – mcrvaz Nov 07 '17 at 11:06