Lazy Load Data with Ionic 2

Mike Hartington
InstructorMike Hartington

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

A common UI pattern in mobile apps is to be able to “pull” down on a list and fetch more data, or scroll and load more. This kind of pattern is built into Ionic with the ionRefresher component and ionInfiniteScroll component.

Infinite Scroll and Refresher can be heavily customized as well. Both components allow you to change what is shown as the user begins to perform their action. This allows for a much more customized experience!

[00:00] Loading more data into our app can easily be done by using the ion-refresher component, and ion-infinite-scroll component. We'll look at the ion-refresher component first. To add this functionality, we'll modify our template and add the ion-refresher component between our ion-content and ion-list.

[00:19] Inside of that, we'll create an ion-refresher content, and ten close it out. Now to create the functionality we'll bind to the event ionRefresh, and call a method doRefresh, passing in the event.

[00:40] In our class, we'll create our doRefresh method and then call our service to get data from the random user API. With the data that comes back from our request, we'll take our original people array and use unshift plus a spread operator to add new data the front of our list.

[01:03] To notify our refresher that the request is done, we'll complete our subscribe and in the done callback, we'll call event.complete, this will notify the refresher that it should be done refreshing. We'll save, and then be able to pull down in our app and load more data.

[01:25] For infinite scroll, we more or less can follow the same pattern. We can go back to our template, and actually can take our ion-refresher component, copy and paste it below ion-list, and then rename it to ion-infinite-scroll. We'll also rename our event and method from ionRefresh and doRefresh to ionInfinite and doInfinite.

[01:48] We'll go back to our class and duplicate our doRefresh method. We'll rename it to doInfinite, and this time instead of unshift, we'll use push instead. Now we'll be able to pull for more data and scroll to load more as well.