如何在onSnapshot外部从Firestore数据库获取数据 [英] 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:
在添加侦听器之前
Before adding listener
添加侦听器后
获得数据
这可能不是您期望的顺序.但这很好地解释了为什么您的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:
- get asynchronous value from firebase firestore reference
- Why are the Firebase API asynchronous?
- How to get a single document data in a Firebase Firestore (without promises)
这篇关于如何在onSnapshot外部从Firestore数据库获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!