【问题标题】:AngularFire2 query not returning document IDAngularFire2 查询不返回文档 ID
【发布时间】:2019-03-14 18:12:18
【问题描述】:

我在服务中使用 AngularFire2 从 Firestore 集合中获取数据。代码如下所示:

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

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

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

【问题讨论】:

    标签: angular firebase google-cloud-firestore angularfire2


    【解决方案1】:

    你可以像这样使用快照:

    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

    snapshotChanges()

    它是什么? - 将数据的 Observable 作为 DocumentChangeAction 返回。

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

    【讨论】:

    • 谢谢 Nadhir,看起来像这样!
    猜你喜欢
    • 2020-01-20
    • 1970-01-01
    • 2019-08-18
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多