我想获取添加的实体的ID,但是由于此实体尚未添加,因此它不返回任何内容。如何调用此服务函数并等待直到它完成?
//Service file
AddItem(data, downloadURLs) {
data.upload = downloadURLs;
// Add a new document with a generated id
var addDoc = this.db.collection('items').add(data).then(ref => {
var updateNested = this.db.collection('items').doc(ref.id).update({
id: ref.id
});
});
}
//Here I call it
onAddItem() {
if (this.AddItemForm.valid) {
var result = this.itemService.AddItem(this.AddItemForm.value, this.uploadService.downloadURLs);
}
}
答案 0 :(得分:0)
我无法测试代码段,但我猜这可能对您有用。 只需用async等待将您对db的调用(返回承诺)包装起来。在我的示例中,addItem方法返回一个包含您添加的项目的Promise。
//Service file
async addItem(data, downloadURLs) {
data.upload = downloadURLs;
// Add a new document with a generated id
const ref = await this.db.collection('items').add(data);
const item = await this.db.collection('items').doc(ref.id).update({ id: ref.id });
return item;
}
//Here I call it
async onAddItem() {
if (this.AddItemForm.valid) {
const item = await this.addItem(this.value, this.uploadService.downloadURLs);
//do something with the item here
}
}