What is snapshotchanges in firestore

妖精的绣舞 提交于 2020-04-08 04:40:06

问题


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
  });

}

回答1:


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.




回答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 => {
      });



回答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);


来源:https://stackoverflow.com/questions/48608769/what-is-snapshotchanges-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!