Search code examples
typescriptfirebasegoogle-cloud-firestoreangularfire2

get the ID of collection document from Firestore using Angularfire2 in ionic 3


I'm trying to get id of the collection to use it in the ionic page:

this is my interface:

  export interface Item { 
  categoryOfPost: string; 
  imageUrl: string;
  nameOfPost: string;
  cityOfPost: string;
  createdDate: string;
  currencyOfPost: string;
  priceOfPost: number;
  typeOfPost: number;
  statusOfPost: string;
  id?: string;
}

 private itemsCollection: AngularFirestoreCollection<Item>;
  items: Observable<Item[]>;

and this is the content of the getPosts function

  this.itemsCollection = this.afs.collection('posts', ref => ref.orderBy('createdDate', 'desc'));
  this.items = this.itemsCollection.valueChanges(); 

when i want to view the content i use:

 <ion-card style="margin-bottom: 25px; background-color: burlywood" *ngFor="let item of items | async">
    <ion-item text-wrap  style="margin-bottom: 25px; background-color: burlywood"> 
        <ion-list >       
          <ion-item> 
            <img src="{{ item.imageUrl }}">            
            cityOfPost: {{ item.id }}            
          <button ion-button (click)="detailpage(item.id)">click to test  </button>
          </ion-item>           
        </ion-list>  
    </ion-item>
  </ion-card>  

I can show everything on the HTML EXCEPT for the ID it comes UNDEFINED ???? what is the correct way to display it ???

Thank you.


Solution

  • This is because by using valueChanges() "all Snapshot metadata is stripped and just the method provides only the data", as explained in the doc.

    You should use snapshotChanges(), see the doc here which says: "Why would you use it? - When you need a list of data but also want to keep around metadata."