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() {
}
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:
I have changed following things:
ReactUI
instantiation inside promise callbackbase64
parameter asstring
getBase64
function call, fromthis.processImage()
tothis.processImage
so it is passing callback function and not result ofprocessImage
function.I hope this helps!