从Firebase存储返回下载URL的功能

时间:2016-07-22 09:58:01

标签: javascript angularjs firebase firebase-storage

我正在编写此函数以在我的角度应用程序中用于评估ng-repeat列表中的ng-src。我需要使调用同步,以便每次调用函数时值都是正确的。问题是:

为什么此代码返回一个值:

var storage = firebase.storage();
var returnVal; //causes sync issues
var getImageUrl = function (time) {
    storage.ref('images/' + time + '.jpg').getDownloadURL().then(function (url) {
        returnVal = url;
    });
    return returnVal;
};

但这不起作用:

var storage = firebase.storage();
var getImageUrl = function (time) {
    var returnVal; //so that this is specific to the function
    storage.ref('images/' + time + '.jpg').getDownloadURL().then(function (url) {
        returnVal = url; //I simply want to return the value of 'url'
    });
    return returnVal;
};

我是如何让getImageUrl()函数从.then返回url的?

这是文档链接:https://firebase.google.com/docs/storage/web/download-files

最后我将其转换为$ scope函数,使用与此类似的函数:

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

3 个答案:

答案 0 :(得分:4)

您的函数的任何变体都不会返回不是nullundefined的值。在继续执行下面的代码之前,您正在执行异步调用,不会等待结果。例如:

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)

您不知道异步调用何时会返回数据,但它始终位于return returnVal;之后,因此returnVal为空。

我推荐这个:

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

然后在你看来:

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

加载所有这些内容的时间取决于$scope.messages的大小。如果数量很大,我建议您更改数据结构,这样就不必多次调用数据库。

答案 1 :(得分:1)

theblindprophet的答案包含一个很好的解释,说明为什么你当前的代码不起作用并且工作解决方案。

作为替代方案,您可以简单地返回getDownloadURL()返回的所谓承诺。我没有经过测试,但希望Angular自动接受承诺。

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

在您的HTML中,您只需保留:

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

答案 2 :(得分:0)

您可以在 firebase-storage

中使用 ajax 作为下载文件
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;
}

如何使用?

const myImage = downloadImage('myPath.png', '../default.png');
相关问题