Skip to content Skip to sidebar Skip to footer

Function That Returns Download URL From Firebase Storage

I'm writing this function to use in my angular app to evaluate ng-src in an ng-repeat list. I need to make the calls synchronous so that the value is correct each time the function

Solution 1:

Neither variation of your function will ever return a value that isn't null or undefined. You are performing an asynchronous call that will not wait for the result before continuing to execute the code below it. For example:

var storage = firebase.storage();
// Execute (1)
var getImageUrl = function (time) {
    // Execute (2)
    var returnVal;
    // Execute (3)
    storage.ref('images/' + time + '.jpg').getDownloadURL().then(function (url) {
        // Execute (unknown)
        returnVal = url;
    });
    // Execute (4)
    return returnVal;
};
// Execute (unknown times)

You have no idea when the async call will return the data, but it will always be after return returnVal; therefore returnVal is null.

I recommend this:

$scope.images = [];
$scope.messages = { // whatever };
for (m in $scope.messages) {
    storage.ref('images/' + time + '.jpg').getDownloadURL().then(function (url) {
        // Might need $scope.$apply(function() {} ) surrounding
        $scope.images.push(url);
    });
}

Then in your view:

<div ng-repeat="image in images">
    <img ng-src="{{ image }}">
</div>  

The time for all this to load is dependent on the size of $scope.messages. If there are a large amount I would recommend changing your data structure so you do not have to make multiple calls to the database.


Solution 2:

theblindprophet's answer contains a great explanation of why your current code doesn't work and a working solution.

As an alternative, you can simply return the so-called promise that getDownloadURL() returns. I haven't tested, but expect Angular to pick the promise up automatically.

var storage = firebase.storage();
var getImageUrl = function (time) {
    return storage.ref('images/' + time + '.jpg').getDownloadURL();
};

And in your HTML you just keep:

<div ng-repeat="message in messages">
    <img ng-src="{{ getImageUrl(message.time) }}">
</div>

Solution 3:

You can use ajax for downlead file in firebase-storage

const link = linkYourFirebaseImage + folderStoreImage + '2F' + fileName;
// example: const link = https://firebasestorage.googleapis.com/v0/b/myApp.appspot.com/o/myDir%2F1608378322792.PNG;


function downloadImage(fileName, defaultImage) {
  if (fileName.length == 0) return defaultImage;

  let imageUrl;
  $.ajax({
    type: "GET",
    async: false,
    url: link ,
    success: function (response) {
      imageUrl = `${link}alt=media&token=${response.downloadTokens}`;
    },
  });

  return imageUrl;
}

How to use ?

const myImage = downloadImage('myPath.png', '../default.png');

Post a Comment for "Function That Returns Download URL From Firebase Storage"