Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Firestore Collection Snapshot Changes

I am using FireStore, I simply need to display the collection list data onto the component and next to each item that is displayed be able to delete the item.

I need to use SnapShotChanges() in order to get the ID for my delete method.

Here is my code. Nothing is console being console logged. I am on using Angular 7.

  userCollection: AngularFirestoreCollection<any>;
  collection: any;

  constructor(private afs: AngularFirestore, private adminService: AdminServiceService) { }

  ngOnInit() {
    this.userCollection = this.afs.collection<any>('valuation');
    this.collection = this.userCollection.snapshotChanges().pipe(
      map(actions => {
        actions.map(a => {
          console.log(a.payload.doc.data);
          console.log(a.payload.doc.id);
        })
      }
    ))
  }

Here is my template:

<tbody *ngFor="let o of collection | async">
      <tr>
        <td scope="row">
          {{o.address}}
        </td>
        <td scope="row">
          {{o.name}}
        </td>
        <td scope="row">
          {{o.email}}
        </td>
        <td scope="row">
          {{o.phone}}
        </td>
        <td scope="row">
          <button mat-button color="warn" class="delete" type="button" (click)="delete(o)">Delete</button>
        </td>
      </tr>
    </tbody>
like image 499
user10181542 Avatar asked Jan 01 '26 07:01

user10181542


1 Answers

When you use snapshotChanges AngularFirestore gives you the Document as well as the id of the document.

You can then extract the actual value of the document using payload.doc.data() on the action.

Give this a try:

import { Component } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  userCollection: AngularFirestoreCollection<any>;
  collection: any;

  constructor(private afs: AngularFirestore) { }

  ngOnInit() {
    this.userCollection = this.afs.collection<any>('valuation');
    this.collection = this.userCollection.snapshotChanges()
      .pipe(
        map(actions => actions.map(a => a.payload.doc.data()))
      );
  }
}

Here's a Working Sample StackBlitz for your ref.

like image 146
SiddAjmera Avatar answered Jan 02 '26 20:01

SiddAjmera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!