0

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
cakePHP
  • 425
  • 1
  • 4
  • 23

1 Answers1

3

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);
    });
Hydra
  • 950
  • 4
  • 7
  • 1
    `collectionChanges` only fetches changed doc instead of whole collection like `snapshotChanges` do. – cakePHP Sep 15 '21 at 05:18
  • @cakePHP I updated my answer to use `collectionSnapshots` which will return the whole collection like `snapshotChanges` – Hydra Sep 15 '21 at 11:37