Angular 2 uses RxJS Observables for events (i.e. valueChanges and server requests handling Http. Observables are similar to Promises as they both deal with async behavior, but they are much bigger abstraction that provides iterable streams and operations for creating, transforming, filtering, combining and error handling.
In this article, I will share some ideas how you can use RxJS Observable streams to handle server side pagination. I will use GitHub Search API as example. You find full source code and live example at https://github.com/tb/angular2-reactive-examples.
To make a GitHub Search API request we will need 3 params: search term, page number and per page count. We can get those values from valueChanges. To combine the parameters we can use combineLatest which will emit params whenever any of params has emitted a new item. For the page and perPage we can initiate the values using startWith.
Mapping params$ to results$
Once we have the params we can map them to API requests using switchMap like this:
There are 3 possible values for the results$ stream:
- if search term is empty string – we return empty results
- if search term is provided – we make the request
- if error occurs – we return empty results with error details
The results$ stream abstracts the API and ensures we always get same format of the results data that sets UI into expected state.
Updating pagination based on results$
Finally, we need to update the pagination UI. To do this, we combine totalCount$ stream with perPage$ stream and generate pages numbers for page dropdown.
Angular 2 Observables unify UI events and asynchronous API requests handling and allow us to express application business logic in new way. In this post I have shared some of my experiences with Rx Observables. On the GitHub project page I have included plan for further development of this example https://github.com/tb/angular2-reactive-examples#github-search-example. For questions and suggestions please use Github project issues.