【问题标题】:getDownloadURL() return's undefined result for variablegetDownloadURL() 返回变量的未定义结果
【发布时间】:2019-01-25 00:27:42
【问题描述】:

我想使用她的“url”(getDownloadURL), 可能在 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);

【问题讨论】:

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


    【解决方案1】:

    当您调用 getDownloadURL 时,下载 URL 会从 Firebase 服务器异步加载。由于这可能需要一些时间,因此调用的代码after 会立即继续。然后,当下载 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 的代码都需要在 inside 然后是 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 都以这种方式运行,我建议现在花一些时间研究它,这样你就不会那么频繁地对它感到困惑了。一些来源:

    【讨论】:

      猜你喜欢
      • 2017-10-18
      • 2020-07-19
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 2020-08-21
      相关资源
      最近更新 更多