如何从 onSnapshot 之外的 Firestore DB 获取数据 [英] How to get data from firestore DB in outside of onSnapshot
问题描述
当我尝试从 firestore 获取值并放入变量时结果未定义,但在控制台中工作.
Result undefined when I try to get value from firestore and put to a variable, but works in console.
我的代码:
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
回调.
The data is loaded from Cloud Firestore asynchronously. Because this may take some time, the code after the callback immediately continues. Then when the data is available, Firestore calls your onSnapshot
callback.
通过添加一些日志语句最容易查看发生了什么:
It's easiest to see what's happening by adding a few log statements:
console.log('Before adding listener');
this.db.collection('Users').doc(uid).get()
.then((docSnapshot) =>{
console.log('Got data');
});
console.log('After adding listener');
当你运行这段代码时,它会打印:
When you run this code, it prints:
添加监听器之前
添加监听器后
获得数据
这可能不是您期望的顺序.但这完美地解释了为什么您的 console.log(perfil)
打印 undefined
:数据尚未加载!
This is probably not the order you expected. But it explains perfectly why your console.log(perfil)
prints undefined
: the data hasn't been loaded yet!
因此,所有需要访问数据的代码都需要在 onSnapshot
回调中.例如:
Because of this, all code that needs access to the data needs to be inside the onSnapshot
callback. For example:
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);
});
}
});
有关这方面的更多信息,请参阅:
For more on this, see:
这篇关于如何从 onSnapshot 之外的 Firestore DB 获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!