【问题标题】:Angular / Firestore - Await a firestore document queryAngular / Firestore - 等待 firestore 文档查询
【发布时间】:2020-12-12 23:17:58
【问题描述】:

我的服务中有一个用于创建新文档的函数。此新文档的其中一个值需要来自存储在另一个文档中的值。

如何在更新我的新文档之前等待文档查询 (getDoc) 的返回值?

我想象的步骤(如果我错了请纠正我)是:

  1. 调用getDoc 函数并返回一个值,比如说“生日”
  2. 返回此值后,调用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,而是使用原生 firestore 查询来查询文档,如果存在,则使用数据调用文档添加函数。我觉得没关系。

标签: typescript google-cloud-firestore async-await angularfire


【解决方案1】:

我建议阅读官方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
    });
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    • 2021-05-04
    • 2018-07-12
    • 2021-02-18
    相关资源
    最近更新 更多