[英]AngularFire - How to map firestore documents to an array on valueChanges?
In my angular web app I'm using the angularfire library to interact with firestore.在我的 angular web 应用程序中,我使用 angularfire 库与 firestore 进行交互。
In the constructor of a component I would like to subscribe to a collection of documents and map the docs to an array when the value changes function is triggered.在组件的构造函数中,我想订阅文档集合,并在触发值更改函数时将文档映射到数组。
I can easily display the list in the front end using the provided syntax.我可以使用提供的语法轻松地在前端显示列表。
//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>
However, I need an array (or object) of the documents in that collection because I need to do some logic to render other things.但是,我需要该集合中文档的数组(或对象),因为我需要执行一些逻辑来呈现其他内容。 For example I have a "isChecked" function that decides if a checkbox is checked based on if an item exists in that collection of documents.
例如,我有一个“isChecked”函数,它根据该文档集合中是否存在某个项目来决定是否选中复选框。
async isChecked(itemID) {
if(items[itemID]) {
return true;
} else {
return false
}
}
So, how can I get the documents to another variable and keep it updated on valueChanges?那么,如何将文档获取到另一个变量并在 valueChanges 上保持更新?
this.itemsCollection.valueChanges()
.pipe(
tap(res => {
this.items = res;
})
)
.subscribe();
and after this need to remove the async pipe from html, in this case u will be able to use items as object or array, not as observable, maybe it will be easier for you.并且在需要从 html 中删除异步管道之后,在这种情况下,您将能够将项目用作对象或数组,而不是可观察的,也许对您来说会更容易。 Also don't forget to unsubscribe in ngOnDestroy
也不要忘记在 ngOnDestroy 中取消订阅
你可以使用 rxjs 地图操作符
this.items = this.itemsCollection.valueChanges().pipe(map (res) => ... );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.