April 20, 2016
  • Tutorials
  • Ionic
  • Ionic 2
  • Tutorials

10 Minutes with Ionic 2: Calling an API

Andrew McGivery

My name is Andrew McGivery. I ...

2020 Update: Building Ionic 1, 2, or 3 apps? We recommend Ionic 4 and above – learn how to migrate. For an updated way to make API calls natively, see the Capacitor Community HTTP plugin.

Getting up and running with Ionic 2 using the Ionic CLI is super simple for anyone with web development experience. In our first two articles 10 Minutes with Ionic 2: Hello World and 10 Minutes with Ionic 2: Adding Pages and Navigation, we looked at the basics of creating an Ionic app. In this article, we’ll build on what we learned and look at calling backend APIs using a class.

Ionic Start

We’ll start by creating an app with the blank template, using ionic start.

ionic start apiApp blank --v2 --ts

As described in the first post of this series, we now have some basic plumbing, including a home page.

Default File Structure

Creating a New Provider

Let’s look at adding a new provider (also known as a service), which will be used to make an HTTP request to an API. Similar to the last post, where we created a page, the CLI makes this significantly easier by providing automatic provider generation, using ionic g. After changing into the project directory (cd apiApp), let’s create a new provider called PeopleService, using the CLI.

ionic g provider PeopleService

The CLI will generate the an @Injectable class called PeopleService in app/providers/people-service/people-service.ts.

New project structure with about page

This class will have the basic boilerplate code inside of a load method to make an HTTP request.

load() {
  if (this.data) {
    // already loaded data
    return Promise.resolve(this.data);
  }

  // don't have the data yet
  return new Promise(resolve => {
    // We're using Angular HTTP provider to request the data,
    // then on the response, it'll map the JSON data to a parsed JS object.
    // Next, we process the data and resolve the promise with the new data.
    this.http.get('path/to/data.json')
      .map(res => res.json())
      .subscribe(data => {
        // we've got back the raw data, now generate the core schedule data
        // and save the data for later reference
        this.data = data;
        resolve(this.data);
      });
  });
}

Random User API

The Random User Generator is a free API that generates data of fake users, including names, emails, pictures, etc. It is a very helpful API for doing mockups and learning. Making an HTTP request to https://randomuser.me/api/ will return a JSON response similar to the following:

{
  "results":[
    {
      "gender":"male",
      "name":{
        "title":"mr",
        "first":"eugene",
        "last":"jordan"
      },
      "location":{
        "street":"3277 green rd",
        "city":"australian capital territory",
        "state":"queensland",
        "postcode":275
      },
      "email":"eugene.jordan@example.com",
      "login":{
        "username":"beautifulbutterfly703",
        "password":"redhot",
        "salt":"tva1i6Oo",
        "md5":"a4231f30aa1fcfe46e4c7c4537a4bf11",
        "sha1":"d6051a921eba285bbeccd95388332f92a50047ce",
        "sha256":"093b0e1b429a105902f91e4be28c9dc12629701924312d63d55cdfd556d54c38"
      },
      "registered":1000882268,
      "dob":537587321,
      "phone":"02-4894-6208",
      "cell":"0477-498-405",
      "id":{
        "name":"TFN",
        "value":"571061435"
      },
      "picture":{
        "large":"https://randomuser.me/api/portraits/men/12.jpg",
        "medium":"https://randomuser.me/api/portraits/med/men/12.jpg",
        "thumbnail":"https://randomuser.me/api/portraits/thumb/men/12.jpg"
      },
      "nat":"AU"
    }
  ],
  "info":{
    "seed":"8eb0b2c2e327a185",
    "results":1,
    "page":1,
    "version":"1.0"
  }
}

If we modify our request to https://randomuser.me/api/?results=10, the results array in the response will contain ten users. Let’s put this in our PeopleService. We will need to make a couple of changes to the code the provider gave us. First, let’s put in the URL:

this.http.get('https://randomuser.me/api/?results=10')

Currently, our code stores/returns the whole response. However, we only want to return the results array in the response. We’ll modify the .subscribe method:

.subscribe(data => {
  this.data = data.results;
  resolve(this.data);
});

Now, our method, when called, will return a promise, which will resolve with an array of users when we get a response back from the API.

Calling PeopleService

Let’s take a look at calling our PeopleService and outputting the results as a list on our home page. First, inside app/pages/home/home.ts, we need to import our service:

import {PeopleService} from '../../providers/people-service/people-service';

Next, in our @Page decorator, we will need to add our service as a provider.

@Page({
  templateUrl: 'build/pages/home/home.html',
  providers: [PeopleService]
})
export class HomePage {

Now, we can add a constructor to our page, create a people property, import the PeopleService, and assign the PeopleService to a property of the class.

export class HomePage {
  public people: any;

  constructor(public peopleService: PeopleService){

  }
}

Let’s add a method to our HomePage class called loadPeople that will call our peopleService.load method and assign the result of the promise in a people property of the class.

loadPeople(){
  this.peopleService.load()
  .then(data => {
    this.people = data;
  });
}

Finally, we will call this method from our constructor.

export class HomePage {
  public people: any;

  constructor(public peopleService: PeopleService){
    this.loadPeople();
  }

  loadPeople(){
    this.peopleService.load()
    .then(data => {
      this.people = data;
    });
  }
}

Now that our class is getting the data, let’s modify our template for this page (app/pages/home.html) to list out users with their picture, first name, last name, and email. We’ll accomplish this by looping through our people array property using ngFor.

<ion-navbar *navbar>
  <ion-title>
    Home
  </ion-title>
</ion-navbar>

<ion-content class="home">
  <ion-list>
    <ion-item *ngFor="#person of people">
      <ion-avatar item-left>
        <img src="{{person.picture.thumbnail}}">
      </ion-avatar>
      <h2>{{person.name.first}} {{person.name.last}}</h2>
      <p>{{person.email}}</p>
    </ion-item>
  </ion-list>
</ion-content>

Serve

Finally, in the CLI, we’ll run ionic serve to view our app in the browser:

ionic serve

You should end up with something similar to the following in your browser:

Screenshot of Browser Output

Conclusion

In under ten minutes, using the power of the Ionic CLI and some simple code, we have created an app that interacts with a backend API. This functionality is needed to create most apps, and this ability to get it working quickly will help you greatly on your journey toward creating the next #1 app in the app stores!


Andrew McGivery

My name is Andrew McGivery. I ...