Get document id firestore angular

筅森魡賤 提交于 2021-01-29 16:32:10

问题


I tried to create a auto document id in firestore and get the document id in angular 8 using the following code but I am getting the document Id after the completion of the execution.Can anyone help me?Thanks in advance

        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:


So you're using promises which means the callbacks in then and catch will be called after everything else - in this case they will actually be called after the final console.log(component.docid). If you can specify your method as async (See MDN on async function) then it should make it easier to reason about it. Rewriting your code would then look like this:

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);


来源:https://stackoverflow.com/questions/61373170/get-document-id-firestore-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!