Ionic 3 (2+) - Retrieving Data from Remote Rest API Server with HTTP Module and RxJS -- Words (733)

Ionic
Ionic 3 - Retrieving Remote Server Data with HTTP Module and RxJS

In this Ionic 3 (2+) tutorial we will cover how to use the HTTP module to retrieve data or consume an API from some remote server.

As you know, when building apps, you can either store data locally with some SQLite database or local storage, use a remote server to store your data or use no data storage at all (in rare cases).

In this tutorial we'll cover the second case by building a simple Ionic 3 app which connects to a remote server and retrieve data then display it using an Ionic List component.

We will also see how to use the Reactive library RxJS to work with observables.

We are not going to reinvent the wheel by building a Rest API server but instead we are going to use JSONPlaceholder a fake online REST API for testing and prototyping.

Now lets get started.

Create a New Ionic 3 (2+) Project


First of all, lets generate a new project based on Ionic 3 (2+) and Ionic CLI v3. For a tutorial see: Ionic 3, Create First Project

ionic start ionic-3-rest-api 

Wait for the CLI to do its job then

cd ionic-3-rest-api 
ionic serve 

Generating an Ionic 3 Service/Provider


Now lets generate a provider which will contain all code responsible for connecting to remote API and retrieve data.

ionic g provider RemoteService

Don't forget to add this provider to the list of app providers.

Go to src/app/app.module.ts

Import the module

import { RemoteService } from '../providers/remote-service';

Then add it

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

Adding HTTP Module to Our Project


Since we are going to make use of the HTTP module we need to add it to the list of imports inside src/app/app.module.ts

So go ahead, start by importing the HTTP module

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

Then add it to the imports array

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

In the RemoteService provider you'll find that HTTP is already imported and injected via service constructor so all you need to do is to start using it.

Calling the Rest API


As I said earlier, we are going to use a fake API available from https://jsonplaceholder.typicode.com/.

It has many endpoints such as:

/posts  100 items

/comments   500 items

/albums 100 items

/photos 5000 items

/todos  200 items

/users  10 items

Lets retrieve the data from /posts endpoint

First add a method to the RemoteService service and also a member variable which holds the API endpoint

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



getApiUrl : string = "https://jsonplaceholder.typicode.com/posts";

getPosts() {

    return  this.http.get(this.getApiUrl)
            .do((res : Response ) => console.log(res.json())
            .map((res : Response ) => res.json())
            .catch(error => console.log(error));
}

The do operator allows you to execute some operations on response, in our case we'll just log the response to the console.

Next open your home page src/pages/home/home.ts then

Import RemoteService and inject it in page constructor.

Add a member variable of type Array to host our posts.

Add a method to fetch posts.

export class HomePage {
    postList = [];

    constructor(private remoteService : RemoteService){
        this.getPosts();
    }
    getPosts(){
        this.remoteService.getPosts().subscribe((data)=>{
            this.postList = data;
        });
    }
}

Displaying Data with An Ionic List


After getting remote data from the remote rest api, lets display it using a list.

Go ahead and open src/pages/home/home.html then add an ion-list to ion-content

<ion-content padding>
<h2>Posts</h2>
<ion-list>
    <ion-item *ngFor="let post of postList">
    { { post.title } }
    </ion-item>
</ion-list>
</ion-content>

Now you can serve your app with ionic serve to test if the app is working as expected.

You can also use other HTTP methods such as post, put or delete methods.

Conclusion


We have seen how we can use the HTTP module and RxJS library to retrieve data from a remote Rest API server.



mrnerd is a Web Entrepreneur & Developer, Digital Marketer and a Passionate Blogger. He writes about software and website development,money making tips and SEO etc.. He is a tech addict and a computer geek with a lot of hobbies.