How to paginate to previous page using AngularFire

2020-05-27 23:58发布

问题:

Sorry I have seen this question has been asked many times in different ways here such as:

  • Howto paginate back to previous pages in a Angular(6) and firebase Firestore setup
  • How to paginate Firestore dataset by individual page?

But NONE of the answers really explain the solution or are understandable.

Also I went though many tutorials such as:

  • https://howtofirebase.com/firebase-data-structures-pagination-96c16ffdb5ca
  • https://rexrainbow.github.io/phaser3-rex-notes/docs/site/firebase-firestore/#paginate

To details:

So here is what I have done so far

let query = ref.orderBy(orderBy, asc ? 'asc' : 'desc').limit(limit);
        if (startAfter) {
          // Thiis works as it should
          query = query.startAfter(startAfter);
        }
        if (endBefore) {
          // This here does not work or give the correct results. I get the first page. 
          query = query.endBefore(endBefore);
        }
        return query;

So:

query = query.startAfter(startAfter); works as expected.

However:

query = query.endBefore(endBefore) does not end before that document I think it ends up to the limit.

回答1:

As of firebase@7.3.0 you can use the Query.limitToLast(n: number) method - makes it much easier to move backward with paginated data.

Your implementation details might look something like this:

function nextPage(last) {
   return ref.orderBy('age').startAfter(last.age).limit(3);
}

function prevPage(first) {
   return ref.orderBy('age').endBefore(first.age).limitToLast(3);
}


回答2:

So I think I solved it by a comment inspired by the github issue mentioned above:

Supposing you have this array and you are sorting ascending

A,
B, 
C,
D,
E,
F, 

And you have a page limnit of 2 results

Then when you are in the third page you should have

E,
F

Now you need to go to previous page and what you need todo is:

  1. Reverse the sorting order and our data should be [F,E,D,C,B,A]
  2. startAfter the first document of the currently viewed page (in our case E)
  3. Query the firestore to get the results (eg with your limit of 2). You should get with reverse order and starting after E and that is [D,C]
  4. Reverse the above array so it will be [C,D]
  5. Done