问题
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