首先,导入 AngularFirestore 和 Observable 对象: import { AngularFirestore } from '@angular/fire/firestore'; import { Observable } from 'rxjs';
在组件的构造函数中注入 AngularFirestore: constructor(private afs: AngularFirestore) {}
使用 AngularFirestore 中的 collection() 方法获取目标集合,并调用 snapshotChanges() 方法获得文档的快照: const collection = this.afs.collection('目标集合'); const snapshot = collection.snapshotChanges();
使用 map() 方法从快照对象中提取文档的 ID,并将其存储在一个数组中: const ids$ = snapshot.pipe( map(changes => changes.map(c => c.payload.doc.id)) );
接下来,订阅我们的 Observable 对象,并在回调函数中处理所需的数据: ids$.subscribe(ids => console.log(ids));
最终,我们将在控制台中看到所需的文档 ID 数组。