getDownloadURL()返回变量的未定义结果

时间:2018-08-18 00:24:47

标签: typescript firebase ionic-framework ionic3 firebase-storage

我想使用她(getDownloadURL)的“ URL”, 可能在this.url这样的变量中。但是this.url返回的所有内容都是不确定的结果。 (我已经建立了所有与firebase和import的连接,等等) 有人知道是否存在一种实现方法吗? 预先感谢。

example image of the app running

  var storage = firebase.storage();
  var storageRef = storage.ref();
  const spaceRef = storageRef.child(`Profis/${this.EMAIL}.png`);
  spaceRef.getDownloadURL().then(function(url){this.url = url})



console.log("teste: " + this.url);

1 个答案:

答案 0 :(得分:1)

当您调用getDownloadURL时,下载URL将从Firebase服务器异步加载。由于这可能需要一些时间,因此调用之后的代码 会立即继续。然后,当下载URL从服务器返回时,Firebase会调用您在then回调中指定的代码。

最简单的方法是在代码中放置一些日志语句:

var storage = firebase.storage();
var storageRef = storage.ref();
const spaceRef = storageRef.child(`Profis/${this.EMAIL}.png`);
console.log("Before calling getDownloadURL()");
spaceRef.getDownloadURL().then(function(url){
  console.log("Got download URL");
});
console.log("After calling getDownloadURL()");

运行此代码时,输​​出为:

  

在调用getDownloadURL()之前

     

调用getDownloadURL()后

     

获得下载网址

这可能不是您所期望的。但这确实解释了为什么testUrl在打印时未定义:该值尚未从服务器返回。

由于这个原因,所有需要下载URL的代码都必须在内部中,然后进行then()回调(或从内部调用)。所以:

var storage = firebase.storage();
var storageRef = storage.ref();
const spaceRef = storageRef.child(`Profis/${this.EMAIL}.png`);
spaceRef.getDownloadURL().then(function(url){
  this.url = url
  console.log("teste: " + this.url);
});

对于那些刚开始调用异步Web API的开发人员来说,这是一个极为常见的困惑源。由于有许多API都是以这种方式运行的,因此我建议现在花一些时间研究它,以免您对它的使用感到困惑。一些来源:

相关问题