Search code examples
javascriptangularfirebasegoogle-cloud-firestoreangularfire

handle snapshotChanges in firestore collection using AngularFire


I have running my application perfectly with

"@angular/fire": "^6.1.5",
"@angular/core": "~12.0.2"

and it was like

Service.ts

getInboxCollection(userId: string) {
 return this.firestore.collection(`/user/${userId}/inbox/`).snapshotChanges().pipe(
       map(
         changes => {
           return changes.map(
             a => {
              const data: any = a.payload.doc.data();
              data.id = a.payload.doc['id'];
              return data;
            });
        })
    );
}

Component.ts

this.service.getInboxCollection(this.userId).subscribe((res: any) => {
    console.log(res);
}

Now I have moved to the latest version of AngularFire that is

"@angular/fire": "^7.0.4",

And new changes are

service.ts

import { doc as fireDoc, docData, Firestore, docSnapshots } from '@angular/fire/firestore';

getInboxCollection(userId: string) {
 const refOfInbox = fireCollection(this.firestore, `/user/${userId}/inbox/`);
    return docSnapshots(fireDoc(refOfInbox)).pipe(map(res => {
      const data = res.data();
        data['id'] = res.id;
        return data;
    }))
}

Component.ts

this.service.getInboxCollection(this.userId).subscribe((res: any) => {
    console.log(res);
}

But I am getting undefined on console.
As per this official document docSnapshots data is available with accessing the firebasse document only.
https://github.com/angular/angularfire/blob/master/docs/version-7-upgrade.md

But how to get data from firebase collections using docSnapshots or other method with realtime changes ?
Please help me with a better approach.
Thanks in advance.


Solution

  • I've refactored your code to return data the way you're used to using angular/fire 7. Like docSnapshots on an individual document, you can use collectionChanges on a collection. Make sure your paths are correct or data will not be returned.

    Service:

    import {collection, collectionSnapshots, doc, docSnapshots, Firestore} from '@angular/fire/firestore';
    
    
      getInboxCollection(userId: string) {
        const refOfInbox = collection(this.firestore, `/user/${userId}/inbox/`);
        return collectionSnapshots(refOfInbox).pipe(map(res => res.map(data => {
          const id = data.id
          const docData = data.data()
          return {...docData, id}
        })));
    

    component:

        this.service.getInboxCollection(this.userId).subscribe((res: any) => {
          console.log(res);
        });