Ad
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.
Ad
Answer
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
Ad
source: stackoverflow.com
Related Questions
- → Make a Laravel collection into angular array (octobercms)
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → Angularjs not working inside laravel form
- → Analysis of Flux implementations
- → how to write react component to construct HTML DOM
- → angular ng-repeat and images in a row
- → Conditional BG Color on AngularJS
- → Should I 'use strict' for every single javascript function I write?
- → getting the correct record in Angular with a json feed and passed data
- → "Undefined is not a function" at .toBe fucntion
- → angularjs data binding issue
- → Angular / JavaScript auto hydrate an instance
- → Convert generic text string in json object into valid url using Angular
Ad