Saturday, 24 March 2018

How to Make a HTTP Call and Fetch Data in Ionic 2 and 3

In this Post we are going to see on, how to make a http request/call and fetch the response data in ionic 2 & 3 framework.

This post assumes that you already have the ionic project created and running.

lets create a page in our project to implement the HTTP Call request.Now, Execute the below command to create home page.

ionic generate page home

Now, navigate to the page folder that you just created, ie navigate to src/pages/home directory.

Open home.ts and modify your code as shown below.

Modify home.ts file

home.ts



import { Component } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { NavController } from 'ionic-angular';
import 'rxjs/add/operator/map';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public items: any;
  constructor(public navCtrl: NavController, public http: Http) {
  
  }

  ionViewDidLoad(){
    console.log("View Did Load")
  }

  CallApiWithGet(){
    this.http.get('https://www.reddit.com/r/gifs/new/.json?limit=10')
    .map(res => res.json())
    .subscribe(data => {
        console.log(data);
        this.items = data.data.children;
    });
  }


  CallApiWithPost(){
    let headers = new Headers();
    headers.append('Content-Type,'application/json');
    
    let body = {
      message: "Hi there my friend !!"
    }

    // Please change the url.

    this.http.post('http://localhost:8040/api/test',JSON.stringify(body),{headers: headers})
    .map(res => res.json())
    .subscribe(data => {
        console.log(data);
    });
  }
}

Above Code Expalanation

First we must import http & map operator for the http request to work properly without any errors.

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

Next, inject Http into the home pages constructor.

We have CallApiWithGet() function, which calls a get request. we use get to retrieve the JSON data from the URL provided. Here we also have map & subscribe , to explaing in short, the http.get returns the result in the form of an Observable, then map converts the result into a JSON form, and then the subscribe allows us to access the returned data.

Next, CallApiWithPost() function is used to post data to the server. similar to the above explanation we get the data. but what the difference here is that, we have a body and a header here to pass along with the url.

body contains the data we want to send to the server. where as Content-Type in header.append tells the client what the content type of the returned content is.

Now change your home.html to look as follows.

Modify home.html file

home.html



<ion-header>

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

  </ion-header>

  <ion-content padding>
    <div style="text-align:center;" style="box-shadow: 0 4px 10px 0 rgba(0,0,0,0.2), 0 4px 20px 0 rgba(0,0,0,0.19);text-align: 
  center;">
     <button ion-button (click)="">Get</button>

     <button ion-button color="secondary" (click)="">Post/button>   
    </div>

    <ion-item *ngFor="let item of items">
      <img [src]="post.data.url" />
    </ion-item>

  </ion-content>

Now save the file and run the project, you will get an error saying " No http Provider ". To solve it simply import http module to app.module.ts file.

Modify app.module.ts file

app.module.ts



import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
 
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
 
@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}


That's it for this Post, if you have any queries regarding the post, please feel free to comment below.

0 comments:

Post a Comment