FSP
FSP

Reputation: 133

AngularFire - Firestore - How to get sub collection and merge into HTML

I have a scenario at the moment where I have a collection of issues which i successfully fetch. In firestore, each issue (issues > issueID) has a sub-collection called images.

In that collection there are doc id's per image. (issues > issueID > images > imageID). I have a page that's displaying all issues, and I'd like to show all related image per issue also.

In my HTML below i have added a comment of where i would like the issue images to go.

Desired result:

etc

Get Issues

 this.issuesCollection = this.afs.collection<any>(`users/${this.userID}/projects/${this.project_id}/issues`, ref => ref.orderBy('issue_order'));
      // this.issues = this.issuesCollection.valueChanges();   
      this.issues = this.issuesCollection.snapshotChanges().pipe(
        map(actions => actions.map(a => {
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;
          return { id, ...data };
        }))
      );

HTML

<ul>
   <li *ngFor="let issue of issues | async">
      {{issue.issue_title}}
      <ul>
         <li>
             <!-- THIS IS WHERE I WOULD LIKE THE IMAGES PER ISSUE TO GO -->      
         </li>
      </ul>
    </li>
</ul>

Images Collection Reference This is the location of the images, where id would be the ID of the issue. This hasn't been hooked up, but is where the location of the images would be.

this.imagesCollection = this.afs.collection<any>(`users/${this.userID}/projects/${this.project_id}/issues/${id}/images`);
this.images = this.imagesCollection.snapshotChanges()

Upvotes: 2

Views: 1854

Answers (1)

Dominik Šimon&#237;k
Dominik Šimon&#237;k

Reputation: 1602

There is new feature in firebase called Collection group query, which definitely can help in your case. But unfortunately i dont think this has been already implemented in angularfire2.

You can use RxJS MergeMap

  const collection = this.firestore.collection('users');
  return  collection.valueChanges.pipe(
    mergeMap( (users: User[]) =>  
               this.firestore.doc(`stories/${users[0].uid}`).
                        valueChanges().pipe(map(
                          (storie) => Object.assign({}, {users[0].uid, ...users[0], ...stories}
                      ))
           ))
   );

Upvotes: 2

Related Questions