且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检索单个Firestore文档的ID?

更新时间:2021-07-02 22:32:06

您正在以可观察的方式获取数据const data = a.payload.doc.data() as Country

You are getting data as Observable const data = a.payload.doc.data() as Country

您需要订阅才能获取数据

you need to subscribe to get the data

this.docId.subscribe(docs => {
  docs.forEach(doc => {
    console.log(doc.id);
  })
})

这是推荐的方法

export class AppComponent implements OnInit {
title = 'Firestore - Documents';

private countryRef: AngularFirestoreCollection<Country>;
docId: Observable<Country[]>;

constructor( private afs: AngularFirestore ) {

    this.countryRef = this.afs.collection('Country', ref => ref.where('code', '==', 'za'));

    this.docId = this.countryRef.snapshotChanges().map( changes => {
        return changes.map(a => {
            const data = a.payload.doc.data() as Country;
            const id = a.payload.doc.id;
            return { id, ...data };
        });
    });

this.docId.subscribe(docs => {
  docs.forEach(doc => {
    console.log(doc.id);
  })
})

}

  ngOnInit() {}

}

使用angularfire2从Firestore检索数据的最常见做法是.valueChanges().snapshotChanges(). valueChanges()方法仅提供数据.它会剥离所有元数据,包括keys.另一方面,.snapshotChanges()将返回所有数据,包括元数据.

Most common practice to retrieve data from firestore using angularfire2 are .valueChanges() and .snapshotChanges(). valueChanges() method provides only the data. It strips all meta data including keys. On other hand .snapshotChanges() will return all data including metadata.

在您的代码中,当您执行const data = a.payload.doc.data() as Country;时,它仅返回带out键的数据.并且当您将其映射到const data时,id将被忽略,因为您指定了构造函数,如id?: string;空安全模式.

In your code when you do const data = a.payload.doc.data() as Country; it only returns the data with out key. and when you map it to const data id will be ignored because you specified your constructor like id?: string; null safe mode.

然后您获得ID const id = a.payload.doc.id;,并需要以某种方式将其返回给interface.通过执行此return { id, ...data };,您还将返回所有ID为ID的数据.和...data将在id之后一个接一个地附加其所有字段.您可以了解有关此功能的更多信息

Then you get the id const id = a.payload.doc.id; and somehow you need to return it the way you want your interface is. By doing this return { id, ...data }; you are returning all data with id too. and ...data will append all its field one by one after id. you can learn more about this feature here Hope you understand.