AngularFire - 如何将 firestore 文档映射到 valueChanges 上的数组?
AngularFire - How to map firestore documents to an array on valueChanges?
在我的 angular 网络应用程序中,我使用 angularfire 库与 firestore 交互。
在组件的构造函数中,我想订阅一个文档集合,并在触发值更改函数时将文档映射到一个数组。
我可以使用提供的语法轻松地在前端显示列表。
//component constructor
constructor(private afs: AngularFirestore) {
this.itemsCollection = afs.collection<Item>('items');
this.items = this.itemsCollection.valueChanges();
}
//component template
<ul>
<li *ngFor="let item of items | async">
{{ item.name }}
</li>
</ul>
但是,我需要该集合中文档的数组(或对象),因为我需要执行一些逻辑来呈现其他内容。例如,我有一个 "isChecked" 函数,它根据某个项目是否存在于该文档集合中来决定是否选中复选框。
async isChecked(itemID) {
if(items[itemID]) {
return true;
} else {
return false
}
}
那么,我怎样才能将文档获取到另一个变量并使其在 valueChanges 上保持更新?
你可以使用 rxjs map 操作符
this.items = this.itemsCollection.valueChanges().pipe(map (res) => ... );
this.itemsCollection.valueChanges()
.pipe(
tap(res => {
this.items = res;
})
)
.subscribe();
并且在此之后需要从 html 中删除异步管道,在这种情况下,您将能够将项目用作对象或数组,而不是可观察的,也许这对您来说会更容易。
也不要忘记在 ngOnDestroy
中退订
在我的 angular 网络应用程序中,我使用 angularfire 库与 firestore 交互。
在组件的构造函数中,我想订阅一个文档集合,并在触发值更改函数时将文档映射到一个数组。
我可以使用提供的语法轻松地在前端显示列表。
//component constructor
constructor(private afs: AngularFirestore) {
this.itemsCollection = afs.collection<Item>('items');
this.items = this.itemsCollection.valueChanges();
}
//component template
<ul>
<li *ngFor="let item of items | async">
{{ item.name }}
</li>
</ul>
但是,我需要该集合中文档的数组(或对象),因为我需要执行一些逻辑来呈现其他内容。例如,我有一个 "isChecked" 函数,它根据某个项目是否存在于该文档集合中来决定是否选中复选框。
async isChecked(itemID) {
if(items[itemID]) {
return true;
} else {
return false
}
}
那么,我怎样才能将文档获取到另一个变量并使其在 valueChanges 上保持更新?
你可以使用 rxjs map 操作符
this.items = this.itemsCollection.valueChanges().pipe(map (res) => ... );
this.itemsCollection.valueChanges()
.pipe(
tap(res => {
this.items = res;
})
)
.subscribe();
并且在此之后需要从 html 中删除异步管道,在这种情况下,您将能够将项目用作对象或数组,而不是可观察的,也许这对您来说会更容易。 也不要忘记在 ngOnDestroy
中退订