【问题标题】:Get document id firestore angular获取文档 ID Firestore 角度
【发布时间】:2020-04-22 19:05:51
【问题描述】:

我尝试在 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);

【问题讨论】:

  • 我不明白你在问什么。到目前为止你写的有什么问题?
  • @DougStevenson 值 component.docid 没有更新任何值,直到我退出函数,但希望它在函数内完成,以便我可以保存文档数组中的id

标签: angular typescript google-cloud-firestore


【解决方案1】:

所以你使用了 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);

【讨论】:

  • 非常感谢@pmccloghrylaing 解决了我的错误,就像宝石一样工作
猜你喜欢
  • 2018-04-23
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 1970-01-01
  • 2019-07-04
  • 2020-03-09
相关资源
最近更新 更多