AngularFire-如何在valueChanges上将Firestore文档映射到数组?

问题描述 投票:0回答:2

在我的角度网络应用中,我正在使用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上保持更新?

angular typescript firebase angularfire
2个回答
1
投票
this.itemsCollection.valueChanges()
.pipe(
  tap(res => {
   this.items = res;
  })
)
.subscribe();

并且在这之后需要从html中删除异步管道,在这种情况下,您将能够将项目用作对象或数组,而不是可观察的,也许对您来说会更容易。另外,不要忘记在ngOnDestroy中退订


1
投票

您可以使用rxjs映射运算符

this.items = this.itemsCollection.valueChanges().pipe(map (res) => ... );
© www.soinside.com 2019 - 2024. All rights reserved.