使用 AngularFire 中的 SnapshotChanges 在对象中映射文档引用

Map Document Reference In Object with SnapshotChanges in AngularFire

我有一个 class 如下所示:

export class Business {
  name: string;
  docRef: DocumentReference;

  constructor(name: string, docRef: DocumentReference) {
    this.name = name;
    this.docRef = docRef;
  }
}

我想要的是能够在获取数据时轻松地在 Firestore 中操作此对象以存储 DocumentReference。例如目前我有以下内容:

this.firestore.collection<Business>('businesses').doc<Business>(id).valueChanges();

...但我知道我需要使用 snapshotChanges 来获取元数据(即 DocumentReference)。

如何在检索 DocumentReference 时轻松地将其映射到我的 Business 对象中?感谢您的帮助。

答案比我预期的要简单,所以我决定回到这里 post 看答案是否对任何人有帮助。

给定 Business 的示例,将以下方法添加到 Business:

static fromFirestore(doc: DocumentSnapshot<Business>): Business {
  return ({
    name: doc.data().name,
    docRef: doc.ref,
  });
}

然后在阅读时调用以下内容:

this.firestore.collection<Business>('businesses').doc<Business>(id).snapshotChanges().subscribe((value) => {
      this.business = Business.fromFirestore(value.payload);
    });

或者,如果您想 return 一个可观察的字符串,请执行以下操作:

return this.firestore.collection<Business>('businesses').doc<Business>(id).snapshotChanges().pipe(
      map(value => Business.fromFirestore(value.payload))
    );

希望这对某人有所帮助。