1,307 Views

Ionic 2, Making a HTTP request to get JSON Data From Backend Server

In this tutorial we are going to load some JSON (javascript object notation) data in our Ionic 2 application.

Objectives of this tutorial

  1. Generate Ionic 2 app using Ionic CLI
  2. Serve the project and view in our browser
  3. Create a provider using Ionic CLI
  4. Use Http service to perform Get request and subscribe to return data
  5. Use ngFor and ngIf angular directive in our view to display our data

Let’s begin by generating an ionic 2 project using Ionic CLI. If you are unfamiliar with creating Ionic 2 apps using Ionic CLI read our getting started tutorial.

$ ionic start HttpProject --v2
$ cd HttpProject

This is will create a new Ionic 2 project in the folder HttpProject with Ionic tabs starter. To check that your project is properly created serve the project in the browser.

$ ionic serve

ionic-http1.png

You should be given a server url in your command window generally its http://localhost:8100, opening the link in the browser should give you following view

ionic-http2.png

 

Final result of this tutorial can be found at the following repo

 

All the work related to talking to backend server is done in the provider. It’s a angular 2 concept. In this tutorial we are going to load JSON data from reddit server into our application. Let’s generate a provider to handle talking to reddit server using Ionic CLI.

$ ionic g provider RedditService

Open up your project in your favourite text editor. We are going to use atom. In your projects ‘/src/provider/’ open reddit-service.ts in the editor and paste the following code.

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

@Injectable()
export class RedditService {

 constructor(public http: Http) {
 console.log('Hello RedditService Provider');
 }
 getRemoteData(){
 console.log(this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=10&sort=hot'));
 }
}

Here, we are importing Injectable from angular core to make this an injectable service. Then we are importing Http from angular http that allows us to make http requests. We are also importing rxjs map operator that will allow us to map our http response string to JSON object.

We have added a new function getRemoteDate(), that performs http get request and print’s it in the console. In order for us to be able to use this provider, we need to add this to the app module, that is our default module for ionic project. Open ‘src/app/app.module.ts’ and paste the following line

import {RedditService} from "../providers/reddit-service";

below other import statements, and add RedditService to the providers array as

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

Now, to call the function we just created in the RedditService, we need to call it from our page. We are going to do that from our home page. Open ‘src/pages/home/home.ts’ and paste the following code

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {RedditService} from "../../providers/reddit-service";

@Component({
 selector: 'page-home',
 templateUrl: 'home.html'
})
export class HomePage {

 constructor(public navCtrl: NavController, public redditService:RedditService) {
 }
 ionViewDidLoad(){
 this.redditService.getRemoteData();
 }
}

All we did here is, added an import statement to import our provider, and instantiated our provider in the constructor, and in the ionViewDidLoad() function called our getRemoteData() function. If you have been following the tutorial, your app should already be served in the browser and it should automatically reload to reflect the change. You will not see any change in the view, but you should see the log we printed in the console. Open up your browser console and you should see something like below

ionic-http3.png

Our function is making an Http request and returning an observable. But this is not what we want, we want our JSON data.

An observable is a thing that we can subscribe to, that will emit data over time. So an observable can say something at any time and we must be listening to catch what that observable said. To learn more about observable follow the link.

Change the code of our getRemoteData() function as follows and view console to see what happens

getRemoteData(){
 this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=10&sort=hot')
 .subscribe(data=>console.log(data));
 }

You should see the following output in the console.

ionic-http4.png

Still not exactly what we want. This is an Http request, if we look in, we can find the actually data in this response. This is where the map comes in. We can use map operator to change the response object to get only the data. Change the code of the getRemoteData() function again and view the result.

getRemoteData(){
 this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=10&sort=hot')
 .map(res=>res.json())
 .subscribe(data=>console.log(data));
 }

This should print the actual JSON object in the console as follows.

ionic-http5.png

Finally, this looks like the data we want.

For the last part, we will be displaying the gif in our home page. To do that, change the code of the getRemoteData() function as follows

getRemoteData(){
 return this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=10&sort=hot')
 .map(res=>res.json());
 }

Here, we are returning the observable. Now change the HomePage class in home.ts as follows:

export class HomePage {
 private data:any;
 constructor(public navCtrl: NavController, public redditService:RedditService) {
 }
 ionViewDidLoad(){
 this.redditService.getRemoteData().subscribe(data=>this.data=data.data);
 }
}

Here, we are making a private property named data, and ionViewDidLoad() is subscribing to our Http request and returning data to our data property.

Finally change the code of ‘src/pages/home/home.html’ as follows to show our gifs

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

<ion-content padding>
 <h2>Welcome to Ionic!</h2>
 <ion-list>
 <div *ngIf="data != undefined">
 <div *ngFor="let gif of data.children, let i = index">
 <ion-item *ngIf="gif.data.url.substring(gif.data.url.lastIndexOf('.'),gif.data.url.length)==='.gif'">
 <img [src]="gif.data.url" />
 </ion-item>
 </div>
 </div>
 </ion-list>
</ion-content>

Here, first we are only showing the items if data != undefined. Then using ngFor directive, we are looping through the children object our data and we are only showing the item if the extension is “.gif”. Finally you should see the following output, the gif images may be different than mine.

ionic-http6.png

If your not seeing the images, log your data in console and check to see if there are any .gif urls in the data returned by reddit service.

That’s it, if you have any queries or confusion, feel free to comment. Thank you.

Related Posts

Advancde Ionic Components

If you are a Ionic developer, beginner or expert, you will love this project. Publicly being developed in github, ionic3-components repository hosts […]

Android Launcher App in React Native

A simple custom Android launcher app built with React Native. Find in GitHub A custom Android Launcher made with ReactNativehttps://github.com/lohanidamodar/RNLauncher5 forks.16 stars.0 open […]

This post is trending.

Setting up Ionic View for Testing Ionic App

Introduction Ionic View is by far the best thing Ionic framework provides. The problem with hybrid apps is that we need to […]

%d bloggers like this: