Ionic 2 Consuming REST API

by Didin J. on Mar 01, 2017 Ionic 2 Consuming REST API

Tutorial about how to consuming REST API using Ionic 2 Mobile App with standard Angular HTTP client.

The mean of consuming REST API that we are accessing REST API on the server from Ionic 2 Mobile App. So, this tutorial will need a server that serves REST API. There's is a lot of free REST API for testing purpose, but previously we have been writing about creating REST API in the different category. You can grab code sample and run on your machine. Here's they are:

- Grails 3 REST Web Service
- Node.js, Express.js and Mongoose.js REST API

That REST server run with MongoDB, for that you have prepared and install MongoDB first. If you like to use external REST web service, this is one of them JSONPlaceholder.


1. Create New Ionic 2 Project

Almost all of our tutorial starting with new project creation. So, open your terminal or cmd then go to your projects folder. Type this command.

ionic start IonicRestCall --v2

This command will create new App with the name 'IonicRestCall'. Go to this newly created folder.

cd IonicRestCall

Always test the newly created project to make sure there is no error in the current environment.

ionic serve --lab


2. Generate Ionic 2 Service

Next, we have to make a service or provider file for implement REST call. For that, just type this command.

ionic g provider RestapiService

Open that newly generated provider file using your text editor or IDE.

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

/*
  Generated class for the Restapi provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class RestapiService {

  constructor(public http: Http) {
    console.log('Hello Restapi Provider');
  }

}

As you can see, default generated provider is using Angular HTTP client which already injected to the constructor. Next, register this service in 'app.module.ts'. Open and edit 'app.module.ts' then add this import.

import { RestapiService } from '../providers/restapi-service';

Then add in provider @NgModule.

providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, RestapiService]


3. Create REST API call

Now, it's time to make a REST API call from provider file. To make this practice simpler, we will use existing free REST API for testing on the Internet. For Edit provider file then declare REST URL variable below class name.

apiUrl = 'https://jsonplaceholder.typicode.com';

Create function for getting users data.

getUsers() {
  if (this.data) {
    return Promise.resolve(this.data);
  }

  return new Promise(resolve => {
    this.http.get(this.apiUrl+'/users')
      .map(res => res.json())
      .subscribe(data => {
        this.data = data;
        resolve(this.data);
      });
  });
}

That getUser function will check if data already loaded then return existing data. Otherwise, it will load new data and resolve to Promise.

Now, it's time to use service from the controller. For this example, we will access data from REST API in the home page. Open and edit app/pages/home/home.ts then add this import.

import { RestapiService } from '../../providers/restapi-service';

Inject this service in the constructor.

constructor(public navCtrl: NavController, public restapiService: RestapiService) {}

Declare the variable to hold data below class name.

users: any;

Create new function for call the service.

getUsers() {
  this.restapiService.getUsers()
  .then(data => {
    this.users = data;
  });
}

Call this function from constructor.

constructor(public navCtrl: NavController, public restapiService: RestapiService) {
  this.getUsers();
}


4. Display data in View

To displaying data in the view, open and edit app/pages/home/home.html then replace tags inside ion-content tag with this tags.

<ion-content padding>
  <h2>User List</h2>
  <ion-list>
    <ion-item *ngFor="let user of users">
      {{user.name}}
    </ion-item>
  </ion-list>
</ion-content>

Now, run the app then view in the browser and you will see the list of users like below.

ionic serve

Ionic 2 Consuming REST API - User List


5. Post data to REST API

After we successfully get list of the user, now we trying to save new user to the REST API. We can use generated about page for creating user form. Open and edit app/pages/about/about.html then replace all tags inside ion-content tag with this.

<ion-content padding>
  <h2>Add User</h2>
  <form (ngSubmit)="saveUser()">
    <ion-item>
      <ion-label>Name</ion-label>
      <ion-input type="text" [(ngModel)]="user.name" name="name"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Username</ion-label>
      <ion-input type="text" [(ngModel)]="user.username" name="username"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Email</ion-label>
      <ion-input type="email" [(ngModel)]="user.email" name="email"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Phone</ion-label>
      <ion-input type="text" [(ngModel)]="user.phone" name="phone"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Website</ion-label>
      <ion-input type="url" [(ngModel)]="user.website" name="website"></ion-input>
    </ion-item>
    <ion-item-divider color="light">Address</ion-item-divider>
    <ion-item>
      <ion-label>Street</ion-label>
      <ion-input type="text" [(ngModel)]="user.address.street" name="street"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Suite</ion-label>
      <ion-input type="text" [(ngModel)]="user.address.suite" name="suite"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>City</ion-label>
      <ion-input type="text" [(ngModel)]="user.address.city" name="city"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Zip Code</ion-label>
      <ion-input type="text" [(ngModel)]="user.address.zipcode" name="zipcode"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Geo</ion-label>
      <ion-input type="text" [(ngModel)]="user.address.geo.lat" name="lat" placeholder="Latitude"></ion-input>
      <ion-input type="text" [(ngModel)]="user.address.geo.lng" name="lng" placeholder="Longitude"></ion-input>
    </ion-item>
    <ion-item-divider color="light">Company</ion-item-divider>
    <ion-item>
      <ion-label>Name</ion-label>
      <ion-input type="text" [(ngModel)]="user.company.name" name="name"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Business</ion-label>
      <ion-input type="text" [(ngModel)]="user.company.bs" name="bs"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Catch Phrase</ion-label>
      <ion-input type="text" [(ngModel)]="user.company.catchPhrase" name="catchPhrase"></ion-input>
    </ion-item>
    <button ion-button type="submit" block>Add User</button>
  </form>
</ion-content>

Create a new function in 'restapi-service.ts' to post new user. Open and edit app/providers/restapi-service then add this function.

saveUser(data) {
  return new Promise((resolve, reject) => {
    this.http.post(this.apiUrl+'/users', JSON.stringify(data))
      .subscribe(res => {
        resolve(res);
      }, (err) => {
        reject(err);
      });
  });
}

Call that post service from controller. But first, declare model variable form the form or data that will be post to REST API.

user = { name: '', username: '', email: '', phone: '', website: '', address: { street: '', suite: '', city: '', zipcode: '', geo: { lat: '', lng: '' } }, company: { name: '', bs: '', catchPhrase: '' }};

Don't forget to import and inject RestapiService.

import { RestapiService } from '../../providers/restapi-service';

constructor(public navCtrl: NavController, public restapiService: RestapiService) {}

Create function for save data.

saveUser() {
  this.restapiService.saveUser(this.user).then((result) => {
    console.log(result);
  }, (err) => {
    console.log(err);
  });
}

Then restart your Ionic 2 app. Open in the browser then test save data.

For put and delete have the same function with the post. And that it's for the basic, next time we will cover more deeply about consuming REST API in Ionic 2 Mobile App. You can get the full source code in my Github. Finally, we need your suggestion to improve this article. Please put your suggestion in the comment below.

Thanks.

 

Send us your email to keep up to date with new articles



Loading…