Firebase range query

会有一股神秘感。 提交于 2019-12-12 03:48:29

问题


Im using AngularFire+Firebase and have data at firebase-database.

Im trying to paginate Data with Smart Table

My problem is that I dont know how to range query without specifying any child i,e fetch records from record # 25 to 35

Below query gives me first 5 records

var queryFIrst = visitRef.startAt().limitToFirst(5);
$scope.Visits = $firebaseArray(queryFIrst);

now Im trying to get records next 5,from 6 to 10 and I tried below

var queryFIrst = visitRef.startAt().limitToFirst(5).endAt().limitToFirst(5);
$scope.Visits = $firebaseArray(queryFIrst);

but it giving error that startAt and endAt can't be used like this with limit


回答1:


In general pagination is not a good fit for Firebase's realtime data model/API. You're trying to model a SQL SKIP operator, which won't work with the Firebase Database.

But if you want to model pagination in Firebase, you should think of having an "anchor point".

When you've loaded the first page, the last item on that page becomes the anchor point. When you then want to load the next page, you create a query that starts at the anchor point and load n+1 item.

In pseudo-code (it's real JavaScript, I just didn't run it):

var page1 = visitRef.orderByKey().limitToFirst(5);
var anchorKey;
page1.on('child_added', function(snapshot) {
  anchorKey = snapshot.key; // this will always be the last child_added we received
});

Now when you want to load the next page of items, you create a new query that starts at the anchor key:

var page2 = visitRef.orderByKey().startAt(anchorKey).limitToFirst(6);

A few things to note here:

  • You seem to be using an approach from the Firebase 1.x SDK, such as an empty startAt(). While that code may still work, my snippets use the syntax/idiom for the 3.x SDK.
  • For the second page you'll need to load one extra item, since the anchor item is loaded for both pages.
  • If you want to be able to paginate back, you'll also need the anchor key at the start of the page.



回答2:


Is that what you needed that time?

visitRef.orderByKey().startAt("25").endAt("35")

I asked a similar question Get specific range of Firebase Database children



来源:https://stackoverflow.com/questions/40721803/firebase-range-query

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