Search code examples
angularhtmltypescriptes6-promisephotoeditorsdk

Capture result of HTML5 FileReader when using promises in async


I have an Angular 4 application where I am reading an image & trying to pass the base64 string to another variable - however I am having an issue due to the async nature of this - the image.src is empty and therefore the value has passed correctly to the image object?

ngAfterViewInit(): void {
    let image = new Image();
    var promise = this.getBase64(fileObject, this.processImage());
    promise.then(function(base64) {
        console.log(base64);    // outputs string e.g 'data:image/jpeg;base64,........'
    });

    image.src = base64; // how to get base64 string into image.src var here??

    let editor = new PhotoEditorSDK.UI.ReactUI({
        container: this.editor.nativeElement
        editor: {
           image: image
        }
    });
}

/**
 * get base64 string from supplied file object
 */
public getBase64(file, onLoadCallback) {
    return new Promise(function(resolve, reject) {
        var reader = new FileReader();
        reader.onload = function() { resolve(reader.result); };
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}

public processImage() {

}

Solution

  • As the code is asynchronous in nature, you will have to wait for the result if you want to use it. In your case, you will have to wait until your promise is resolved. So your code should look like:

    ngAfterViewInit(): void {
       let image = new Image();
       var promise = this.getBase64(this.fileObject, this.processImage);
       promise.then(function(base64: string) {
           console.log(base64);    
           image.src = base64;
    
           let editor = new PhotoEditorSDK.UI.ReactUI({
               container: this.editor.nativeElement
               editor: {
                 image: image
               }
           });
       });
    }
    

    I have changed following things:

    1. I moved code for ReactUI instantiation inside promise callback
    2. Specified type of base64 parameter as string
    3. Fixed typo in getBase64 function call, from this.processImage() to this.processImage so it is passing callback function and not result of processImage function.

    I hope this helps!