Bruno Silvano
Bruno Silvano

Reputation: 284

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?

Upvotes: 1

Views: 941

Answers (1)

FlatLander
FlatLander

Reputation: 1767

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
});

Upvotes: 1

Related Questions