0

我在服务中使用 AngularFire2 从 Firestore 集合中获取数据。代码看起来像这样:

this.db.collection('organizations')
  .valueChanges()
  .pipe(first())
  .toPromise()
  .next(organization => console.log(organization));

控制台正在完全按照预期记录组织对象。但是该对象缺少 Firestore 文档的 ID。

所以我想知道是否可以做一些事情来获取 ID 作为该查询的一部分......

4

1 回答 1

2

您可以像这样使用快照:

private getOrganizations(whereClause: any): any {
        return this.db.collection('organizations')
            .snapshotChanges()
            .pipe(
                map((docs: any) => {
                    return docs.map(a => {
                        const data = a.payload.doc.data();
                        const id = a.payload.doc.id;
                        return {id, ...data};
                    });
                })
            );
    }

有关snapshotChanges检查的更多详细信息:

https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md#snapshotchanges

快照更改()

它是什么?- 作为 DocumentChangeAction 返回一个 Observable 数据。

你为什么要使用它?- 当您需要文档数据但又想保留元数据时。此元数据为您提供了基础 DocumentReference 和文档 id。拥有文档的 id 可以更容易地使用数据操作方法。由于 type 属性,此方法为您提供了与其他 Angular 集成(例如 ngrx、表单和动画)的更多功能。每个 DocumentChangeAction 上的 type 属性对于 ngrx reducer、表单状态和动画状态很有用。它是什么?- 返回一个 Observable 的数据作为

于 2019-03-14T18:46:02.523 回答