简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM