获取文档ID Firestore Angle

时间:2020-04-22 19:05:51

标签: angular typescript google-cloud-firestore

我尝试使用以下代码在firestore中创建自动文档ID,并使用以下代码获取角度为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);

1 个答案:

答案 0 :(得分:0)

因此,您使用的是Promise,这意味着thencatch中的回调将在其他所有事件之后被调用-在这种情况下,它们实际上将在最后一个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);