Calling an API or Making HTTP Requests in IONIC

Let’s learn calling backend APIs in IONIC.

Let’s start by creating an app with the blank template, using ionic-start.

ionic start HTTPapp blank — v2 –ts
cd HTTPapp

Create a New Provider

Add a new provider (also known as a service), which will be used to make an HTTP request to an API.

let’s create a new provider called FirstService using the CLI.

ionic g provider FirstService
// open FirstService
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
export class FirstService {
constructor(private http:Http) {}
GetRequest() {
.map(res => res.json())
.subscribe(data => {console.log(data);},
error => {console.log(JSON.stringify(error.json()));}
PostRequest() {
var headers = new Headers();     
headers.append("Accept", 'application/json'); headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
     let dataToPost = { 
}"http//", dataToPost, options)
.map(res => res.json())
.subscribe(data => {console.log(data);},
error => {console.log(JSON.stringify(error.json()));}
  • Http is service that provides a fairly straightforward way of handling requests.

HTTP calls in Angular 2 will return observable where Angular 1 request will return promises.

  • RxJs in rxjs/add/operator/* stands for Reactive Extensions for JavaScript. It’s a set of libraries which enables us to compose asynchronous/event-based programs using observable collections.

If you’re accessing remote content install Cordova Whitelist plugin:

cordova plugin add cordova-plugin-whitelist

Open www folder and add this security meta tag to index.html file:

cordova plu<meta http-equiv=”Content-Security-Policy” content=”script-src ‘self’ ‘unsafe-eval’ ‘unsafe-inline’ *; object-src ‘self’; style-src ‘self’ ‘unsafe-inline’; media-src *”>gin add cordova-plugin-whitelist

Add Required Platform

ionic platform add android/ios