1

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

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Zaid Mirza
  • 3,540
  • 2
  • 24
  • 40

2 Answers2

2

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.
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks for your answer,I always expect answer from you, Im using Firebase 3.x. however I took that empty startAt() from somewhere on SO.As according to your answer, it means I have to store very start anchor point and last anchor point in the case if user clicks to goto last page or goto first back and whether user going to next or previous page,its must be tracked too. So the result of theory is that it is complex task with Firebase – Zaid Mirza Nov 21 '16 at 16:45
1

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

user25
  • 2,873
  • 2
  • 30
  • 66