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);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.