【问题标题】:How to access the function variable outside of it in typescript..?如何在打字稿中访问它之外的函数变量..?
【发布时间】:2023-04-04 03:43:01
【问题描述】:

这是我将从 firebase 数据库中获取图片值的函数,问题是如何将函数中的 pictures 变量访问到数组,以便我可以遍历它们并将其显示在我的 HTML 上。

cato(){
    var ref = firebase.database().ref("/images");
    var imgref = ref.orderByChild("name").equalTo("nature").once("child_added", function(snapshot) {
        var pictures = snapshot.val();
    });

【问题讨论】:

  • 如果你想在函数外访问变量,你还必须在函数外定义它。
  • 无需重新发明轮子,Firebase 有一个 Angular 库:github.com/angular/angularfire

标签: angular typescript firebase firebase-realtime-database snapshot


【解决方案1】:

once() 方法实际上有一种“承诺的味道”。

所以你可以这样做:

cato() {
     var pictures = null;
     var ref = firebase.database().ref("/images");
     ref.orderByChild("name").equalTo("nature").once("child_added")
         .then(function(snapshot) {
            pictures = snapshot.val();
         });
})

根据您的评论更新:

once() 方法是异步的并返回一个承诺。只有当这个承诺解决时,你才能获得snapshot 的值。如果您想从代码的另一部分调用cato() 函数,您需要注意cato() 函数也将是异步的。

以下方法可以解决问题(注意cato() 函数中的returns):

cato() {
     var ref = firebase.database().ref("/images");
     return ref.orderByChild("name").equalTo("nature").once("child_added")
         .then(function(snapshot) {
            return snapshot.val();
         });
})

// Call the asynchronous cato() function from another part of the code

cato().then(function(picturesArray) {
   yourArray = picturesArray;
})

【讨论】:

  • 但是如何从cato()函数中访问pictures变量并将其分配给数组呢?
  • 我还是没明白你...这是整个组件的代码..:codeshare.io/2BekWm
【解决方案2】:

您可以将回调模式转换为基于承诺的模式,这样您就可以从回调中获取值,如下所示:

async cato(){
  const ref = firebase.database().ref("/images");
  const pictures = await new Promise((resolve, reject) => {
    ref.orderByChild("name").equalTo("nature").once("child_added", function (snapshot) {
      resolve(snapshot.val());
    });
  });
  return pictures;
}

然后你从你的组件中获取图片:

...
async someMethod() {
    this.pictures = await cato();
}

现在您可以在 html 中使用 pictures


注意:如果你的cato函数已经是一个组件的方法,你可以直接在你的cato函数中设置pictures属性。

async cato() {
  const ref = firebase.database().ref("/images");
  const snapshot = await ref.orderByChild("name").equalTo("nature").once("child_added");
  // snapshot is available now
  this.pictures = snapshot.val();
}

【讨论】:

  • 是的,cato 已经是组件的方法,现在我想从cato() 中访问snapshot.val(),这样我就可以将它分配给任何数组并在其中循环我的html。 注意:在我的例子中,snapshot.val() 返回一个数组。
  • 你能添加你的整个组件吗?你确定 cato 是一个组件的方法吗?
  • 它有效,但在我的情况下,我只从所有对象中获得一个属性,即。 picture 所以现在 snapshot.val().picture 返回一个数组,我得到一个值?
  • 实际上你只得到一个新添加到集合中的文档。我不太确定firestore事件,但你必须使用另一个事件,而不是child_added
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-02
  • 2014-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
相关资源
最近更新 更多