javascript - Firestore 获取数据的时间太长,因此我无法显示它
问题描述
我有一个从 Firestore 获取数据的函数:
getLastTime(collectionName: string) {
const docRef = this.afs.firestore.collection(collectionName).doc(this.User).collection('lastTime').doc('lastTime');
docRef.get().then(doc => {
if (doc.exists) {
this.get = doc.data().lastTime;
} else {
this.get = 'Never done';
}
}).catch(error => {
console.log('Error getting document:', error);
});
return this.get;
}
对于我的测试,我实际上在文档“lastTime”中有一个字符串值,它是一个字符串。
在 ngOnInit() 中,我调用了我的函数并 console.log 了结果
this.InjuredLastTime = this.getLastTime('INJURY');
console.log(this. this.InjuredLastTime);
通常我应该在控制台内打印我的字符串,但我没有定义......
也许是因为 Firestore 没有足够快地获取我的数据,但我很惊讶,因为 Firestore 正常速度很快......
解决方案
在docRef.get()
从getLastTime()
. 因此,除非对 firebase 的调用是即时的(例如从不),否则这是行不通的。
正确的解决方案真的取决于你在做什么this.InjuredLastTime
。但一种方法是返回一个承诺并在它准备好后设置它:
getLastTime(collectionName: string) {
const docRef = this.afs.firestore.collection(collectionName).doc(this.User).collection('lastTime').doc('lastTime');
return docRef.get().then(doc => {
if (doc.exists) {
return doc.data().lastTime;
} else {
return 'Never done';
}
}).catch(error => {
console.log('Error getting document:', error);
return null;
});
}
然后,不是同步分配,而是异步执行:
this.getLastTime('INJURY').then(result => { this.InjuredLastTime = result });
推荐阅读
- r - 有人可以帮我正确设置我的 ggplot 图例吗?
- python - 如果相关对象不存在,则撤销排队任务
- dask - 是否有使用 Dask 从当前工作人员获取节点 IP 地址的接口?
- linux - 写入主机操作系统的目录 - 使用 docker-compose 文件传递指令
- c# - 使用 MimeKit 和默认电子邮件发送邮件
- jmeter - Jmeter点对点测试计划出错
- python - 如何在 Python 中选择最后的 3 个日期
- html - SQLite3::SQLException:在“at”附近:语法错误
- docker - 允许容器读取主机网络统计信息,但绑定到 docker 网络
- wordpress - 当短代码参数未传递给 shortcode_atts() 时,有没有办法过滤短代码属性?