angular - 获取文档 ID Firestore 角度
问题描述
我尝试在 Firestore 中创建一个自动文档 ID,并使用以下代码获取 Angular 8 中的文档 ID,但我在执行完成后获取文档 ID。有人可以帮助我吗?提前致谢
this.db.collection("testdata2").add({
"name": "Tokyo",
"country": "Japan",
"Date": this.date
})
.then(function(docRef){
component.docid=docRef.id;
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
console.log(component.docid);
解决方案
因此,您使用的是 Promise,这意味着回调 inthen
并将catch
在其他所有内容之后调用 - 在这种情况下,它们实际上将在 final 之后调用console.log(component.docid)
。如果您可以将您的方法指定为async
(参见MDN on async function),那么它应该更容易推理。重写您的代码将如下所示:
try {
const docRef = await this.db.collection("testdata2").add({
"name": "Tokyo",
"country": "Japan",
"Date": this.date
});
component.docid = docRef.id;
console.log("Document written with ID: ", docRef.id);
} catch (error) {
console.error("Error adding document: ", error);
}
console.log(component.docid);
推荐阅读
- r - 使用 pmap 和 c(...) 第 2 部分
- python - JSON 添加不必要的花括号
- python - RSA 返回非预期结果
- sql - 使用 Postgres SIMILAR TO 和 Spring Data 来匹配列中的子字符串
- rest - REST API 中用于验证答案的正确路径是什么?
- certbot - 我可以告诉 certbot 发送成功续订的电子邮件吗
- ubuntu - 找不到可用的“nginx”二进制文件。确保 nginx 存在,二进制文件是可执行的
- react-native - Expo rtl 禁用组件和所有子组件
- node.js - 如何在 NodeJS 中使用 udh 连接从 smpp 客户端发送的消息
- sonarqube - 线程事件观察程序 java.lang.NoClassdefFoundError 中的异常:Sonar 中的 org.apache.logging.log4j.core.Appender 设置