An Example of Ionic 3 Infinite Scroll or Load More

by Didin J. on Sep 07, 2017 An Example of Ionic 3 Infinite Scroll or Load More

A real example of Ionic 3 infinite scroll or load more using Ionic 3 infinite scroll API by loading data from REST API.

Infinite scroll is the popular replacement for pagination. It has same function as pagination for limiting displayed list of data on the view. So, we will show you the real example infinite scroll on the Ionic 3 mobile app. `The Real Example` means we'll use data from the REST API, not from local array variable. For this tutorial, we use the latest Ionic 3 and Angular 4 version. Before go deeply with the example, you have to prepare the tools, frameworks, modules, and dependencies. The following tools, framework, and dependencies are required for this tutorial:

- Node.js (use stable and recommended version) 
- Ionic 3
- REST API End point
- Terminal or Node Command Line
- Text Editor or IDE

After installing Node.js and able to run Node command line, run this command in the terminal or Node command line to install or update latest Ionic and Cordova.

sudo npm install -g ionic cordova


1. Create New Ionic 3 Angular 4 App

As usual, in our tutorial start by creating new Ionic 3 Angular 4 app from scratch. In the terminal or Node command line run this command.

ionic start ionic-infinite-scroll blank

Next, go to your newly created app folder.

cd ionic-infinite-scroll

Now, test the newly created app to make sure everything working properly by run this command.

ionic serve --lab

You should see this page open automatically on the default browser.

An Example of Ionic 3 Infinite Scroll or Load More - Ionic 3 Home Page


2. Implementing Infinite Scroll or Load More

Now, its a time for implementing infinite scroll or load more feature to the Ionic 3 and Angular 4 app. First, create provider or service for getting data from the REST API. Type this command on the terminal or Node command line to create it.

ionic g provider rest-api

Open and edit `src/providers/rest-api/rest-api.ts` file then make the imports like this.

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

Declare this variable before the constructor.

private apiUrl = 'https://reqres.in/api/';

We are using free REST API service for testing from Resreq. Now, add the function after constructor to getting data from REST API.

getUsers(page): Observable<string[]> {
  return this.http.get(this.apiUrl+"users?page="+page)
                  .map(this.extractData)
                  .catch(this.handleError);
}

Add function for extract data.

private extractData(res: Response) {
  let body = res.json();
  return body || { };
}

Add function to handle the error.

private handleError (error: Response | any) {
  let errMsg: string;
  if (error instanceof Response) {
    const body = error.json() || '';
    const err = body.error || JSON.stringify(body);
    errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
  } else {
    errMsg = error.message ? error.message : error.toString();
  }
  console.error(errMsg);
  return Observable.throw(errMsg);
}

Don't forget to add `HttpModule` to `src/app/app.module.ts`. Open and edit that file then add this import.

import { HttpModule } from '@angular/http';

Add `HttpModule` to `@NgModule` imports, so it will look like this.

imports: [
  BrowserModule,
  IonicModule.forRoot(MyApp),
  HttpModule
],

Now, open and edit current `src/pages/home/home.ts` then add this import.

import { RestApiProvider } from '../../providers/rest-api/rest-api';

Declare this variables before constructor.

data: any;
users: string[];
errorMessage: string;
page = 1;
perPage = 0;
totalData = 0;
totalPage = 0;

Inject `RestApi` provider inside constructor.

constructor(public navCtrl: NavController, public restApi: RestApiProvider) {}

Create function for getting Users data.

getUsers() {
  this.restApi.getUsers(this.page)
     .subscribe(
       res => {
         this.data = res;
         this.users = this.data.data;
         this.perPage = this.data.per_page;
         this.totalData = this.data.total;
         this.totalPage = this.data.total_pages;
       },
       error =>  this.errorMessage = <any>error);
}

Call that function inside constructor body.

constructor(public navCtrl: NavController, public restApi: RestApiProvider) {
  this.getUsers();
}

Create function for implementing infinite scroll.

doInfinite(infiniteScroll) {
  this.page = this.page+1;
  setTimeout(() => {
    this.restApi.getUsers(this.page)
       .subscribe(
         res => {
           this.data = res;
           this.perPage = this.data.per_page;
           this.totalData = this.data.total;
           this.totalPage = this.data.total_pages;
           for(let i=0; i<this.data.data.length; i++) {
             this.users.push(this.data.data[i]);
           }
         },
         error =>  this.errorMessage = <any>error);

    console.log('Async operation has ended');
    infiniteScroll.complete();
  }, 1000);
}

Next, we will implement infinite scroll on the view. Open and edit `src/pages/home/home.html` then replace all `<ion-content>` with this tags.

<ion-content padding>
  <ion-card>
    <ion-card-header>
      Infinity Scroll Example
    </ion-card-header>
    <ion-card-content>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
      </p>
    </ion-card-content>

  </ion-card>
  <ion-list>
    <ion-item *ngFor="let user of users">
      <ion-avatar item-start>
        <img src="{{user.avatar}}">
      </ion-avatar>
      <h2>{{user.first_name}} {{user.last_name}}</h2>
    </ion-item>
  </ion-list>

  <ion-infinite-scroll (ionInfinite)="doInfinite($event)" *ngIf="page < totalPage">
    <ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data..."></ion-infinite-scroll-content>
  </ion-infinite-scroll>
</ion-content>

We put static paragraph because initial data and infinite scroll data show only 3 rows per page, so we need to cover the rest of page with the static paragraph.

Now, you can test run the app in the browser and see infinite scroll or load more functionality working.

That it for now, you can find the full source code on our GitHub.

Thanks!

The following resources might be useful for you:

Loading…