In many cases - for example, when working with very large data-sets - we don't want to work with the full collection in memory. Instead server-side paging is used, where the server sends just a single page at a time.
Usually, we also want to cache pages that already have been fetched, in order to spare the need for an additional request.
The Paginator API provides two useful features:
Caching of pages which have already been fetched.
A pagination functionally, which gives you all the things you need to manage pagination in the application.
First, we need to create a new provider, let’s say we need paginator for our contacts page:
const contactsQuery =inject(ContactsQuery);
You should already be familiar with the above code. This is the regular process of creating a factory provider in Angular. We are creating a new Paginator(), passing the Query we want to use in our pagination.
Non-Angular applications can export the plugin without using DI. For example:
Paginator provides you with a pageChanges observable so you can listen to page changes and call the getPage() method, passing the request function. Paginator expects to get the following fields as part of the response from the server:
If you didn't provide the total property it will default to: response.perPage * response.lastPage
Paginator also exposes all the data that you need to display as well as methods for controlling the page from the UI:
There are times where we want to give our users the ability to filter the data, sort it, or change the number of entries per page. The vital step here is that when we change a filter, sort etc., we want to invalidate the cache, because it may alter the server response. Here is a fully working example of this type of functionality:
Sometimes you want to save the current filters, so if the user navigates from the current route and comes back you want the filter values to persist. Paginator exposes a metadata property where you can set these values. For example: