[英]AngularFire - How to map firestore documents to an array on valueChanges?
在我的 angular web 應用程序中,我使用 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 上保持更新?
this.itemsCollection.valueChanges()
.pipe(
tap(res => {
this.items = res;
})
)
.subscribe();
並且在需要從 html 中刪除異步管道之后,在這種情況下,您將能夠將項目用作對象或數組,而不是可觀察的,也許對您來說會更容易。 也不要忘記在 ngOnDestroy 中取消訂閱
你可以使用 rxjs 地圖操作符
this.items = this.itemsCollection.valueChanges().pipe(map (res) => ... );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.