如何在 onSnapshot 之外从 firestore DB 获取数据

2023-12-12

当我尝试从 firestore 获取值并将其放入变量时,结果未定义,但在控制台中有效。

My code:

this.db.collection('Users').doc(uid).get()
  .then((docSnapshot) => {
    if (docSnapshot.exists) {
      this.db.collection('Users').doc(uid)
        .onSnapshot((doc) => {
          console.log(doc.data()); //working
          perfil = doc.data(); //not working
        });
    }
  });

console.log(perfil); //not working. Display undefined

数据是从 Cloud Firestore 异步加载的。因为这可能需要一些时间,所以回调之后的代码立即继续。然后,当数据可用时,Firestore 会调用您的onSnapshot打回来。

通过添加一些日志语句来查看发生的情况是最简单的:

console.log('Before adding listener');
this.db.collection('Users').doc(uid).get()
.then((docSnapshot) =>{
  console.log('Got data');
});
console.log('After adding listener');

当您运行此代码时,它会打印:

添加监听器之前

添加监听器后

Got data

这可能不是您期望的顺序。但这完美地解释了为什么你console.log(perfil) prints undefined: 数据尚未加载!

因此,所有需要访问数据的代码都需要位于onSnapshot打回来。例如:

this.db.collection('Users').doc(uid).get()
.then((docSnapshot) =>{
  if (docSnapshot.exists) {
    this.db.collection('Users').doc(uid)
    .onSnapshot((doc) => {
        console.log(doc.data());
        perfil = doc.data();
        console.log(perfil);
    });
  }
});

有关这方面的更多信息,请参阅:

  • 从 firebase firestore 引用获取异步值
  • 为什么 Firebase API 是异步的?
  • 如何在 Firebase Firestore 中获取单个文档数据(没有承诺)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 onSnapshot 之外从 firestore DB 获取数据 的相关文章

随机推荐