user8836786
user8836786

Reputation:

AngularFire - How to use snapshot changes and return data as a variable

I currently have a Firestore document query as follows:

  getDocument(){
    this.albumDoc = this.afs.doc<Album>(`albums/abc`);
    this.album = this.albumDoc.valueChanges(); 
  }

The AngularFire documentation states that you can use 'Snapshot' changes for further data. However there isn't an example of how you'd do this. With collection queries, snapshot changes uses a pipe / map followed by a return of the 'data' which you can then assign to variables if you wish.

Is it possible to do the same with Document Queries? I have a firestore value in my document that I want to grab and toy with.

Upvotes: 0

Views: 6643

Answers (1)

Deepankar Singh
Deepankar Singh

Reputation: 193

The major difference between valuechanges() and snapshotChanges() is that the later one provides us with unique document ID assigned to document whereas the former one only supplies us with document values but not with document id.

I'm sharing an example try if possible:

this is my service file :

    import { Injectable } from '@angular/core';
import { Employee } from './employee.model';
import { AngularFirestore } from '@angular/fire/firestore';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  formData: Employee;

  constructor(private firestore: AngularFirestore) { }

  getEmployees() {
    return this.firestore.collection('employees').snapshotChanges();
  }

}

and this is my component.ts file :

    import { Component, OnInit } from '@angular/core';
import { Employee } from 'src/app/shared/employee.model';
import { EmployeeService } from 'src/app/shared/employee.service';
import { AngularFirestore } from '@angular/fire/firestore';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {

  list: Employee[];

  constructor(private service: EmployeeService, private firestore: AngularFirestore) { }

  ngOnInit() {
    this.service.getEmployees().subscribe(actionArray => {
      this.list = actionArray.map(item => {
        return {
          id: item.payload.doc.id,
          ...item.payload.doc.data()
        } as Employee
      })
    });
  }

  onEdit(emp: Employee) {
    this.service.formData = Object.assign({},emp);
  }

  onDelete(id: string) {
    if(confirm("are you sure you want to delete this record ?")) {
    this.firestore.doc('employees/' + id).delete();
    }
  }

}

Upvotes: 5

Related Questions