问题描述
我在用于创建新文档的服务中具有一个功能。此新文档的值之一必须来自另一个文档中存储的值。
在更新新文档之前,如何等待文档查询(getDoc)返回的值?
我想象的步骤(如果我错了,请纠正我)是
- 调用
getDoc
函数并返回一个值,例如“生日” - 返回该值后,请调用
newDocument
函数,以便将birthday
值用于new_value
添加新文档的功能:
newDocument(g){
const newID = this.afs.createId();
this.afs.doc<Interface>(`col/${id}/col/${newID}`).set({
new_value: // needs to come from other query
});
}
查询文档的功能,我需要从中获取数据:
getDoc(ID: string) {
return this.afs.doc<Interface>(`col/${ID}`).valueChanges().pipe(shareReplay());
}
解决方法
我建议您阅读官方的angularfire documents doc,在这里您可以看到有关如何查询和操作文档的基本示例。
在您的情况下,应将文档转换为Promise或在get
调用中,以等待文档上的subscribe()
调用。出于示例目的,我将所有内容都放在同一函数上。
async newDocument(){
const ID = 'some_id';
const docData = await this.afs.doc(`col/${ID}`).get().toPromise(); // Await the doc data
const newID = this.afs.createId();
this.afs.doc(`col/${id}/col/${newID}`).set({
new_value: docData
});
}