Pagination using AngularFire2

两盒软妹~` 提交于 2019-12-03 05:12:08

AngularFire2 does support startAt and endAt according to their source code. Here's how you would limit your query based on a list with a child key of size:

let queryObservable = this.af.database.list('/items', {
  query: {
    orderByChild: 'size',
    startAt: 50,
    endAt: 100
  }
});

This should pull all the items that have a child key of size defined between 50 to 100.

NOTE I have noticed that if I were to pass in a reference object into AngularFire2 instead of a reference path, the query will NOT work! So the code below will still return the list of items but it will not be sorted properly.

let ref = firebase.database().ref('/items');
this.af.database(ref, { query: { orderByChild: 'size' } });

I looked at this problem in a blog post recently, but you bring up an interesting edge case where your total query will be larger than you want to pull. I would solve this with the same methodology as before, but implementing a start at and end at instead of a limitToLast. Also, you use BehaviorSubjects imported from rxjs because they will allow you to get the current value and increment by a certain amount. Example

let firstKey = new BehaviorSubject(''); // import 'rxjs/BehaviorSubject'
let nextKey = new BehaviorSubject('');
let pageSize = new BehaviorSubject(10);

let queryObservable = this.af.database.list('/items', {
 query: {
   orderByKey: true,
   startAt: firstKey,
   limitToFirst: pageSize
 }
});

Now you have a constantly moving window starting with the first key and using the keys as the value you are sorting on. To be able to change the key, you need to store the key you want in a particular place, for example.

queryObservable.subscribe((data) => {
    // angularfire2 adds a $key property to each result in an array
    // Does not handle the edge case at the end of the list
  if (data.length === pageSize.getValue()) {
    nextKey.next(data.$key);
  }
});

To increase and decrease the window, just change the firstKey value to the value of nextKey.

firstKey.next(nextKey.getValue());

You can do all sorts of neat things, like add multiple pages, or go back a page with small tweaks to this methodology. This is as opposed to adding fields that you have to maintain in your database, which can be cumbersome in some cases.

I've also need to do simple paging (Next and Previous) with Angular 2 and Firebase.

My solution is to querying an extra item from the list itemPerPage + 1 and keeping that as reference. Then using the startAt and endAt options I'm able to page next and previous on my data with the reference item.

I've created a Gist to show my solution, hope it can help.

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