Search code examples
angulartypescriptfirebasefirebase-realtime-databaseangularfire2

How do I get the last item added in a Firebase real-time database?


I am using Firebase's real-time database to update values in real-time inside a chart. However, I don't know how to retrieve the last value added to the database only.

I found some explanation in limitToLast and 'child_added' do not work together #1773, but I didn't manage to make it work.

So far, I managed to do this:

this.items = db.list('/items').valueChanges()
this.items.forEach(item => {
  this.data = item;
  this.add(this.data[this.data.length-1])
  console.log(this.data)
})

add(point: any) {
   this.chart.addPoint(point)
}

But I know it is not at all efficient.


Solution

  • From the docs:

    list<T>(pathOrRef: PathReference, queryFn?: QueryFn): AngularFireList<T> {
     const ref = getRef(this.database, pathOrRef);
     let query: DatabaseQuery = ref;
     if(queryFn) {
       query = queryFn(ref);
     }
     return createListReference<T>(query, this);
    }
    

    list() contains a second parameter that will enable you to query, so you can do the following:

    this.items = db.list('/items', ref => ref.limitToLast(2)).valueChanges()
    
    // subscribe to changes
    this.items.subscribe(lastItems =>{
      console.log(lastItems);  
    });
    

    valuChanges() returns an Observable, so you can use subscribe() to receive the values.

    Check here for more info:

    https://github.com/angular/angularfire2/blob/master/docs/rtdb/querying-lists.md