首页 > 解决方案 > 获取文档 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);

标签: angulartypescriptgoogle-cloud-firestore

解决方案


因此,您使用的是 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);

推荐阅读