Bruno Silvano Bruno Silvano - 1 month ago 9
AngularJS Question

Can't return value of fileReader result in AngularJS service

I'm trying to write a service which reads the image file from an HTML input element. I want this service to return the HTML img object with the updated attribute from the read image file (the base64 string). My service is now this:

.service('ReadLocalImageService', [function () {

this.openLocalImage = function (file) {
var img = document.createElement("img");
var fileReader = new FileReader();
fileReader.onload = function (e) {
img.src = e.target.result;
};
fileReader.readAsDataURL(file);
return img.src;
};

}]);


The
img.src
in this case is returned empty, like this:

Console log from img.src

If I put a
console.log(img.src)
inside the
fileReader.onload
, it prints out what I want. It seems like the function
openLocalImage
is returning the
img.src
before
e.target.result
is assigned to it.

I couldn't manage to work this around nor find the correct topic about this problem. Could anyone help me solve this or explain me why it doesn't work?

Answer

Its because img was not loaded yet. Here is a solution

.service('ReadLocalImageService', [function () {

    this.openLocalImage = function (file, callback) {
        var img = document.createElement("img");
        var fileReader = new FileReader();
        fileReader.onload = function (e) {
            img.src = e.target.result;
            callback(img.src);
        };
        fileReader.readAsDataURL(file);
    };

}]);

We will pass a callback function and receive img.src as its param. To use it

ReadLocalImageService.openLocalImage(myImage, function(imgSrc) {
    // use imgSrc
});
Comments