The Official Ionic Blog

Build amazing native and progressive web apps with HTML5

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!

  • Zaier

    Hi,
    I’ve learnt Angular2’s basics… now I want to create a cross-plateforme mobile app using Ionic2 .
    I have 3 questions for you 🙂
    1- what is the difference between (Components vs Pages) specially in term of lifeCycle.
    2-why you choose Promises over Observables… Observable have many advantages and that is why Angular2 used RX_JS.
    3-When we can have a stable version ready for production of Ionic2
    thanks in advance

  • Wittaya Attasiri

    Nice serie!! Keep it going

    • http://www.mcgivery.com/ Andrew McGivery

      Thanks! 🙂

  • void brain

    what if we want to save data in local db?

    • Zaier

      You have to use ngCordova … I don’t have a lot of info about that …
      In Ionic 1 we used to use ngCordova but what about angular2 and typescript … will we have an ngCordova2 or something else…

      • http://www.raymondcamdencom/ Raymond Camden

        Err, why do you say you have to use ngCordova? While you *can* use it, you don’t need to. You can save to LocalStorage, WebSQL (icky, but you can), IndexedDB, or SQLIte via a plugin (and ngCordova has a wrpaper for that). Actually Ionic2 has support for SQLite too.

        I guess my point is – ngCordova isn’t required. 🙂

      • SP1966

        ionic-native replaced ngCordoava in Ionic 2. You can find out more about ionic-native in the Ionic 2 docs.

    • Ravitheja Maddineni
  • Ravitheja Maddineni

    I am getting below error when I tried to run the ionic tutorial project created by using ionic start MyIonic2ProjectSideMenu tutorial –v2

    Could someone help me how to fix this issue.

    > node_modules/ionic-angular/components.core.scss Error: Import directives may not be used within control directives or mixins. on line 34 of node_modules/ionic-angular/components.core.scss @import “fonts/ionicons”; –^

  • http://www.raymondcamdencom/ Raymond Camden

    As just an FYI (told to me by smarter people on Twitter), in the constructor, you do not need this.peopleService = peopleService, since the public modifier in the constructor makes it automatic.

  • http://marcusvbp.com.br/ Marcus VBP

    Hi,

    If I run this tutorial in my device (nexus 5), the list is not rendered. I can get the data (it showed in the console.log()), but the App view continues empty.

    With “ionic serve” I can get the data and the ion-list is rendered.

  • Ravitheja Maddineni

    How can we handle errors when we get some error code from server

  • ze0

    i’m a bit lost with this new things.
    I have a little more complex system.
    for staying in the context, each person have a job, jobs are in another place in the api, so job need a provider
    but i don’t know how to link the whole thing.

    I did a for loop with people and call the job provider for get the job.
    but i only the last people have it’s job set, I know i have to use promise stuff but it’s very different from ionic 1.
    What would you do in my case ?

    i’m not really used to this. it’s a bit new for me.

  • ashraful haque

    not working with my same data http://need4engineer.com/api.php . which is similar to https://randomuser.me/api/?results=5 can anoyone help me ?

  • Ravitheja Maddineni

    I am getting below error when I try to send request with results=1000.

    I am not sure if this is error with angular2?

    angular2-polyfills.js:126 GET https://randomuser.me/api/?results=1000 net::ERR_INCOMPLETE_CHUNKED_ENCODING

  • Graciele E. Victor

    Great tutorial – what comes next?

  • Dave Gadsden

    Hi there, I have an app project that was not created as a –ts project – I therefore get unexpected token error firstly with the public people: any; line – Anyone give me help as to what in this tutorial i need to re-write? Thanks

    • Antonio

      I’ve the same error. Are you able to solve this issue?

  • Il blu

    I get this error while trying to replicate this tutorial:

    EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property ‘data’ of undefined

    Unhandled Promise rejection: Cannot read property ‘data’ of undefined ; Zone: angular ; Task: Promise.then ; Value: TypeError: Cannot read property ‘data’ of undefined(…)

    But I am able to print the values of the JSON. Can someone please explain me this?

    • Audacitus

      You need to explicitly define your json structure in the typescript class that is pulling the Json and make sure they both match. I just found this out.

  • Veysel Kaya

    does not work..:(

  • Long Nguyễn

    i cannot run. Error: Uncaught (in promise)
    Please help me

  • Nikhil Sharma

    Is there any Restfull post api example, which also serves form validation.

  • Carl Rydings

    How do you add headers to the http,get?

  • http://www.marcosborges.com.br Marcos Borges

    Hi,

    i’m having some problems applying this tutorial. I’m only getting a blank page.

    home.ts:
    import {PeopleService} from ‘../../providers/people-service/people-service’;

    @Page({
    templateUrl: ‘build/pages/home/home.html’
    providers: [PeopleService]
    })
    export class HomePage {
    public people: any;

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

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

    and people-service.ts:
    import { Injectable } from ‘@angular/core’;
    import { Http } from ‘@angular/http’;
    import ‘rxjs/add/operator/map’;

    /*
    Generated class for the PeopleService provider.

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

    constructor(private http: Http) {
    this.data = null;
    }

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

    return new Promise(resolve => {
    this.http.get(‘https://randomuser.me/api/?results=10’)
    .map(res => res.json())
    .subscribe(data => {
    this.data = data.results;
    resolve(this.data);
    });
    });
    }
    }

    • Jean-Baptiste

      You need to put this line at the top of home.ts : import {Page} from ‘ionic-angular’;

    • Muhammad Anas

      Same issue happens with me

    • Phil

      Thank you, Marcos, for solving the data variable issue. I also had to change the following to make it work: this.people = data.results;

    • http://bsides.co/ Rafael Pereira

      Have the same issue. @Page is @Component (changed the reference in everything) but still no use. Can’t import the module still.

  • Makarand Mone

    This was very helpful and worked right out of box

  • Emmanuel Ernest

    Hi,
    Do you have some examples including the LoadingController (beta.11) ?
    I want to display a loading spinner while querying a http client…

    Thanks in advance

  • Michael Bishop

    I am getting an error:

    Error TS2304: Cannot find name ‘resolve’.

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

  • http://www.marqmarti.com/ Marq Martí

    Does. Not. Work.

  • M Argus

    Hello there, I’m new on typescript.

    After copy the “people-service” script to my testing project. I got error on my CLI.. It says

    Error TS2339: Property ‘data’ does not exist on type ‘PeopleService’.

    I think it might be because I’m never make a variable ‘data’ on the service file..

    Where to put the varibale ‘data’ ?

    • Massimo Fattorusso

      put this :
      data: any;

      after :
      export class PeopleService {

      • Mario Espinosa

        Thanks

  • Matthew Tan

    Note: @App is deprecated since 2.0.0 beta 8, and is now replaced with @Component

  • http://bsides.co/ Rafael Pereira

    This throws an error I can’t find a way to fix. Changed paths and nothing. Please help.
    Error: src/pages/home/home.ts(4,31): error TS2307: Cannot find module ‘../../../providers/people-service/people-service’.

  • MOSTSELFISHMAN

    Is it possible to see an authentication tutorial?

  • Albert Higgins

    does someone have the completed tutorial code somewhere, like on github? It’s just easier to see exactly what you’re doing if you can see all the code as opposed to snippets

  • Albert Higgins

    anyone getting errors with the template, try changing the # to a let in the *ngFor loop.

  • mash kaponde

    Hi great tutorial thanks, I am new to ionic and this has really got me up and running…..i was wondering, how can i show some loading functionality (spinner) at the begining of the app to block user interaction and only have the spinner disappear after the http get request is complete. I will appreciate and help.

  • Sumedh Bahatkar

    very very helpful tutorial some error is there but thanks to @Albert Higgins provide same source code for this tutorial with slight minor changes

  • vygaio

    Isnt an Observable wrapped inside a promise anti-promise

  • Gabriel Guedes

    *ngFor=”#person of people” is now wrong.
    Change to:
    *ngFor=”let person of people”

  • kyle

    a lot of stuff different now….

  • Guille Acosta
  • dhananjay solankar

    please send the crud of ionic 2 with any database ex.mysql

  • lahiru heshan

    Hi http is not defined always ,i dont know is there any dependency is missed ,can you pleas help with this

  • malathi

    I am getting CORS error when I use the end point
    https://randomuser.me/api/
    I am using localhost to run the application, any ideas?

  • Shalom iluz

    the bug is in the HTML page *person of people it should be let person of people

  • Hextest Test

    Does Not Work.
    Typescript Error
    Cannot find name ‘Page’.
    Please help

  • Ramu

    Hi,
    Good post.
    Can we get a download link as a demo of what has been shown in this article.
    Secondly When I am running `ionic g provider PeopleService` I am only getting a single file in src/providers folder, unlike what it should be `app/providers/people-service/people-service.ts`
    Thanks.

  • Alain Fernandez del Toro

    How could I show the list of persons grouped by Sex, showing the Sex as a ion-list-header?

  • Jijish Thomas

    Hello, i’m having a problem while accessing an array of objects. Please help