Search code examples
angulartypescriptfirebaseangularfire

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.

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.

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?


Solution

  • 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. Also don't forget to unsubscribe in ngOnDestroy