要在AngularFire中显示Firestore集合查询的键和值,可以使用snapshotChanges()
方法来获取集合的快照,并使用map()
操作符来转换快照中的每个文档。
首先,确保已经安装并导入了angularfire2
和rxjs
依赖项。
接下来,在你的组件中,导入必要的AngularFire和rxjs操作符:
import { Component } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
然后,创建一个接口来定义你的Firestore文档的模型:
interface Item {
key: string;
value: string;
}
接下来,在组件类中,创建一个itemsCollection
属性来存储Firestore集合的引用:
@Component({
selector: 'app-items',
templateUrl: './items.component.html',
styleUrls: ['./items.component.css']
})
export class ItemsComponent {
private itemsCollection: AngularFirestoreCollection- ;
items: Observable
- ;
constructor(private afs: AngularFirestore) {
this.itemsCollection = this.afs.collection
- ('items');
this.items = this.itemsCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Item;
const key = a.payload.doc.id;
return { key, ...data };
});
})
);
}
}
在构造函数中,我们使用this.afs.collection('items')
创建了一个对'items'集合的引用。然后,我们使用snapshotChanges()
方法获取集合的快照,并使用map()
操作符将快照中的每个文档转换为我们定义的Item
接口。
在map()
操作符中,我们使用a.payload.doc.data()
来获取文档的数据,使用a.payload.doc.id
来获取文档的键。最后,我们返回一个包含键和数据的对象。
最后,在模板中,我们可以使用async
管道来订阅items
观察者,并显示每个文档的键和值:
-
{{ item.key }}: {{ item.value }}
这样,我们就可以在Angular中使用AngularFire显示Firestore集合查询的键和值了。