等待firebase加载快照

Rob*_*Rob 3 firebase typescript angular google-cloud-firestore

有这两种方法。我有一个在调用this.family之前调用getFamily方法的类,因为onSnapshot尚未完成加载。我该如何重组它,以便对getFamily的调用将等待onsnapshot完成?可以使用诺言吗?

getFamily() {
    return this.family;
}

setFamilyID(familyID) {
    this.familyID = familyID;

    this.db.collection("families").doc(this.familyID).onSnapshot((familyDoc) => {
        console.log("family updated");

        this.family = familyDoc;
    });
}
Run Code Online (Sandbox Code Playgroud)

Bry*_*oth 7

即时的

如果您需要实时更新,请包装 onSnapshotPromise。您需要对返回值进行处理,onSnapshot以便在销毁组件时分离。另外,请确保只拨打resolve一次。

getFamily() {
  return this.family;
}

setFamilyID(familyID) {
  this.familyID = familyID;
  return new Promise((resolve, reject) => {
    var resolveOnce = (doc) => {
      resolveOnce = () => void;
      resolve(doc);
    };
    this.detachFamilyIDWatcher = this.db
      .collection("families").doc(this.familyID)
      .onSnapshot((familyDoc) => {
        console.log("family updated");

        this.family = familyDoc;
        resolveOnce(familyDoc);
      }, reject);
  });
}
Run Code Online (Sandbox Code Playgroud)

就一次

如果您只需要加载一次数据,则使用get代替onSnapshotget返回a Promise,不需要分离。

getFamily() {
  return this.family;
}

setFamilyID(familyID) {
  this.familyID = familyID;

  return this.db
    .collection("families").doc(this.familyID)
    .get().then((familyDoc) => {
      console.log("family updated");

      this.family = familyDoc;
    });
}
Run Code Online (Sandbox Code Playgroud)