Angular / Firestore - 等待 Firestore 文档查询
Angular / Firestore - Await a firestore document query
我在用于创建新文档的服务中有一个函数。此新文档的其中一个值需要来自另一个文档中存储的值。
如何在更新我的新文档之前等待来自文档查询 (getDoc) 的 returned 值?
我想象的步骤(如有错误请指正)是:
- 调用
getDoc
函数和return一个值,比方说'birthday'
- 一旦此值已 returned,调用
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 或在 subscribe()
调用中等待对文档的 get
调用。出于示例目的,我将所有内容都放在同一个函数中。
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
});
}
我在用于创建新文档的服务中有一个函数。此新文档的其中一个值需要来自另一个文档中存储的值。
如何在更新我的新文档之前等待来自文档查询 (getDoc) 的 returned 值?
我想象的步骤(如有错误请指正)是:
- 调用
getDoc
函数和return一个值,比方说'birthday' - 一旦此值已 returned,调用
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 或在 subscribe()
调用中等待对文档的 get
调用。出于示例目的,我将所有内容都放在同一个函数中。
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
});
}