18

this function is called by the constructor. can someone explain in depth to me what it does?

  initializeItems(){
this.travelList$ = this.plsdala.getTravelList()
.snapshotChanges()
.map(
  changes => {
    return changes.map(c=>({
      key: c.payload.key, ...c.payload.val()
    })).slice().reverse();

   //to reverse order
  });

}
Hareesh
  • 6,770
  • 4
  • 33
  • 60
Jennica
  • 327
  • 1
  • 3
  • 15

3 Answers3

25

It is current state of firestore collection. It returns an Observable of data. You would use it whenever you want to be able to get also your metadata as documentID as opposed to using for example valueChanges() which returns Observable containing data saved in document only. It does not contain metadata.

This means that you would usually use valueChanges() to get data and snapshotChanges() whenever you might need metadata, eg. deleting or updating document.

Your code basically gets data and metadata of document and extracts just data from it. Then it reverses the data to go from end of the collection to the beginning.

Robo Bayer
  • 267
  • 2
  • 11
-2

Since the function is asynchronous, it does not wait to finish before continuing with the rest of the code below. So console.log(travelArray) runs even before the data is received. (did not check the below for syntax errors)

let travelArray = [];
this.travelList$.subscribe(res => {
  res.map(c => {
    travelArray.push(c);
  })
})
.subscribe((a: travelArray) => {
       console.log(a);
      }, error => {
      });
Pat
  • 325
  • 2
  • 11
-3

To push the observables into an array do something like this.

let travelArray = [];
this.travelList$.subscribe(res => {
  res.map(c => {
    travelArray.push(c);
  })
})
console.log(travelArray);
Robo Bayer
  • 267
  • 2
  • 11