简体   繁体   English

AngularFire2查询未返回文档ID

[英]AngularFire2 query not returning document ID

I'm using AngularFire2 in a service to get data from a Firestore collection. 我在服务中使用AngularFire2从Firestore集合中获取数据。 The code looks something like this: 代码看起来像这样:

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

The console is logging the organization object exactly as expected. 控制台正在完全按预期方式记录组织对象。 But that object is lacking the id of the Firestore document. 但是该对象缺少Firestore文档的ID。

So I'm wondering if there's something that can be done to get the ID as part of that query... 所以我想知道是否可以做一些事情来获取ID作为查询的一部分...

you can use the snapshot something like this: 您可以使用以下快照:

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};
                    });
                })
            );
    }

For more details about snapshotChanges check this: 有关snapshotChanges更多详细信息,请检查以下内容:

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

snapshotChanges() snapshotChanges()

What is it? 它是什么? - Returns an Observable of data as a DocumentChangeAction. -返回一个Observable数据作为DocumentChangeAction。

Why would you use it? 你为什么要使用它? - When you need the document data but also want to keep around metadata. -当您需要文档数据但又希望保留元数据时。 This metadata provides you the underyling DocumentReference and document id . 该元数据为您提供了DocumentReference和document id的样式。 Having the document's id around makes it easier to use data manipulation methods. 拥有文档的ID可以更轻松地使用数据处理方法。 This method gives you more horsepower with other Angular integrations such as ngrx, forms, and animations due to the type property. 由于type属性,此方法为您提供了与其他Angular集成(例如ngrx,表单和动画)的更多功能。 The type property on each DocumentChangeAction is useful for ngrx reducers, form states, and animation states.What is it? 每个DocumentChangeAction的type属性对于ngrx缩减器,表单状态和动画状态很有用。它是什么? - Returns an Observable of data as a -将数据的Observable返回为

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM