如何获取添加到 Firebase 实时数据库中的最后一项?
How do I get the last item added in a Firebase real-time database?
我正在使用 Firebase 的实时数据库实时更新图表中的值。但是,我不知道如何只检索添加到数据库中的最后一个值。
我在limitToLast and 'child_added' do not work together #1773中找到了一些解释,但我没能成功。
到目前为止,我设法做到了:
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)
}
但我知道它根本没有效率。
来自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()
包含第二个参数,可让您进行查询,因此您可以执行以下操作:
this.items = db.list('/items', ref => ref.limitToLast(2)).valueChanges()
// subscribe to changes
this.items.subscribe(lastItems =>{
console.log(lastItems);
});
valuChanges()
returns 一个 Observable,所以你可以使用 subscribe()
来接收值。
点击此处了解更多信息:
https://github.com/angular/angularfire2/blob/master/docs/rtdb/querying-lists.md
我正在使用 Firebase 的实时数据库实时更新图表中的值。但是,我不知道如何只检索添加到数据库中的最后一个值。
我在limitToLast and 'child_added' do not work together #1773中找到了一些解释,但我没能成功。
到目前为止,我设法做到了:
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)
}
但我知道它根本没有效率。
来自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()
包含第二个参数,可让您进行查询,因此您可以执行以下操作:
this.items = db.list('/items', ref => ref.limitToLast(2)).valueChanges()
// subscribe to changes
this.items.subscribe(lastItems =>{
console.log(lastItems);
});
valuChanges()
returns 一个 Observable,所以你可以使用 subscribe()
来接收值。
点击此处了解更多信息:
https://github.com/angular/angularfire2/blob/master/docs/rtdb/querying-lists.md