This guide will walk you through writing a simple HTTP Rest Angular application. It is also important to mention that we will cover what is now known as Angular (Angular 2|4), not what was used to be known as Angular 1.
 
You will also be able to learn how to use Master-Detail pattern, including how to work with services. I could have made a much shorter walkthrough but this way you will have a usable application you can reuse for some other project.
 
 

Note: If this tutorial was helpful, need further clarification, something is not working or do you have a request for another Ionic post? Furthermore, if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here, again leave me a comment below. I'm here to help you, I expect the same from you. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com, or follow and mention me on twitter (@gajotres). Thanks and have a nice day!

PS. If you want my help, if possible (even if it takes you some time to do that), create a working example I can play with. Use Plunker for AngularJS based questions or jsFiddle for jQuery/jQuery Mobile based questions.


 

Table of Contents

 
Is Ionic (2 or 3) causing you problems? Are you struggling with your application? Trust me, I was in the same situation like you. If you require more information beyond the subject of this article, you will probably find it in a list below. Take a look; if there’s a topic not covered here, leave me a comment, and I will do my best to cover it.
 
 

Preparations

 
Before we can start, make sure your Ionic [2|3] work environment is up and ready. Another important information (I don’t wont to confuse you), what was Ionic 2|4 is now known simply as Ionic. As such, I will refer to it through that name; there will be no version numbers.
 
We will need these:
 
  • Android Environment (or iOS if you’re working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova
 
If you don’t have a prior Ionic installation find more information here: Ionic [2|3] | Installation Guide.
 

1. Update Ionic CLI

 
The last NodeJS version is an imperative here. Without it, we may have a problem while installing/updating Cordova and Ionic. Worst case scenario, any recent version will probably be enough.
 
If your development environment is up and running, just make sure it’s up to date; older versions may not work with this tutorial:
 
npm install -g ionic cordova
 
or to do a simple update:
 
npm update -g ionic cordova
 
 

2. Create A New Project

 
ionic start IonicHTTPRestExample blank
cd IonicHTTPRestExample 
 
You can find a working example at the end of this article if you’re an impatient type. Just follow the provided README.md instructions.
 
Warning: As some of you don't have a prior Ionic CLI experience, from this point and on, every time I tell you to execute something, do that inside an example project folder.
 

3. Add Required Platform

 
Add Android platform:
 
ionic cordova platform add android
 
MacOS users can also add iOS platform:
 
ionic cordova platform add ios
 

Embeded example:

 
Ionic Page Navigation
 

Making REST HTTP calls

 
Before we can start doing REST calls we need to create a component that will do it for us. For this purpose, we will create an injectable service.
 
It looks like this:
 
import { Injectable } from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class MovieService {

    constructor(private http:Http) {

    }

    searchMovies(movieName) {
        var url = 'http://api.themoviedb.org/3/search/movie?query=&query=' + encodeURI(movieName) + '&api_key=5fbddf6b517048e25bc3ac1bbeafb919';
        var response = this.http.get(url).map(res => res.json());
        return response;
    }    
}
 
As you can see, it is just a simple class without a visible view component.
 
Let’s dissect this code.
 
As with any other Angular class, the first thing we need to do is import necessary components:
 
import { Injectable } from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
 
  • The Injectable decorator gives as an ability to use dependency injection application design pattern; which is one of cornerstones of Angular framework.
  • The Http is service that provides a fairly straightforward way of handling requests. Just remember Angular1 $http but with one major difference. HTTP calls in Angular2 will return observables where Angular1 request will return promises.
  • The 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. And if we want to be more specific about a map operator used here, it’s used, so to speak, to transform a collection of items into a collection of different items.
Inject Http service into MovieService class constructor like this:
 
constructor(private http:Http) {

}	
 
This way, http will be available to the rest of the class.
 
Finally, this is how we can parse HTTP response to a more readable format:
 
var url = 'http://api.themoviedb.org/3/search/movie?query=&query=' + encodeURI(movieName) + '&api_key=5fbddf6b517048e25bc3ac1bbeafb919';
var response = this.http.get(url).map(res => res.json());
return response;
 
To make a POST POST request just replace get with post:
 
var response = this.http.post(url).map(res => res.json());
 
This was the easiest walkthrough I could think of.
 
First, we need to include our new service into app.module.ts. Technically, we can also do this on a class level, but that will create us one big problem. If each class creates a separate instance we will not be able to share data among them. So be careful.
 
import { ListPage } from '../pages/list/list';
import { InfoPage } from '../pages/info/info';
import { MovieService } from '../services/rest/movie-service';

@NgModule({
  declarations: [
    MyApp,
    ListPage,
    InfoPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    ListPage,
    InfoPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    MovieService,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
 
Let’s take a look how we can use this service in the List page:
 
import { MovieService } from '../../services/rest/movie-service';
 
Include this service into ListPage class constructor:
 
constructor(public navCtrl: NavController, private movieService: MovieService) {
 
As we want to search movies, we will trigger a REST call on input box input event:
 
<ion-input type="text" (input)="searchForMovie($event, searchKey)"></ion-input>
 
Each time we write a letter it will trigger a REST call to international movie database. After we enter the third letter, IMDB will send us our first response object:
 
if(event.target.value.length > 2) {
	this.movieService.searchMovies(event.target.value).subscribe(
		data => {
			this.movies = data.results; 
			console.log(data);
		},
		err => {
			console.log(err);
		},
		() => console.log('Movie Search Complete')
	);
}
 
Continue to the next page

  • Zeak

    Thanks for the tutorial. I’ve been looking for a working example of making a REST API call with Ionic 2. Too many tutorials use one component to do everything. I appreciate you making a REAL example.

    • You’re welcome, if you have more questions just ask, I’m here to help. Plus I always need recomendations for other articles. 🙂

  • Matej

    There is no movie-info in the project

    • My mistake, I was cutting this example to bare minimum. Unfortunately, I forgot to move two references to movie-info page. It’s fixed now,

  • aluknot

    I don’t understand why you are importing “inject”, whay means meta-data in this case? I don’t get the difference between “constructor(@Inject(Http) http: Http)” and “constructor(http: Http)” like i saw in others examples.

    • Paca-vaca

      I think @Inject here is verbose and mostly useless because what it does is injecting a dependency which token cannot be resolved by the type of the argument provided in the constructor function.

  • Jb

    SyntaxError: Ionic2RESTHttpExample/app/app.js: Unexpected token (10:17) while parsing file: Ionic2RESTHttpExampleappapp.js
    any suggestions?

    • Roy Anon

      Because the project is js, but this example is written in ts, it won’t work. Remove the type, and change the import back to js.

    • Roy Anon

      I wonder why it’s so difficult to search how to handle this injection stuff… I don’t know if that’s correct or not.. In all the injection class, put @Injectable(), and make a function with the appropriate type, like static get parameters() {
      return [[IonicApp], [Platform]];
      }

  • Harish Patel

    i am not able to find the movie details page.

  • Leelar Thaophialuang

    Thank you for updating the version to be Typescript now.

    • You’re welcome, I’m also working on my other tutorials

  • angatlahi

    thanks for the tutorial. appreciate if you can create also CRUD tutorial using firebase

  • Abhinava Y R

    hi am new to ionic, just a day ago started to learn, here you are created with the existing movie database this example is working fine. now just i wanted to know where to change the database name to connect to database which is i want. and also could you please do send materials to my mail id. so that it can help me a lot..
    thank you soo much.

    • Zulham Azwar Achmad

      u cannot set database on mobile script, just imagine that u setup database address on every apk where people download, to setup database name,etc u can use webservice like Restful as bridge between mobile and database
      sry for my bad english hope this can help

  • Abhinava Y R

    now i have got one more doubt, in ionic 1.0, application launching from www/index.html rite? in ionic 2.0 it is not starting from www folder instead it is starting from other file why so? how that movie info.ts movie-list.ts and service.ts files created???
    is it required to generate for all application or it is just enough to keep this file for all project?? i just need more information on this .ts files.

  • Leongnidas

    I downloaded your sample code and running “ionic serve –lab” as it is and all three test mobile frames show blanks.
    My version of ionic from using “ionic -v” is 2.1.4 FYI. wonder if there are any changes in-between ionic updates.

  • Vinicius Gati

    what if we need a success and failure on the get/post?

    • Zulham Azwar Achmad

      you can subscribe it as data and display on your browser console,,
      for example :
      this.http.get(‘someURL’).map(res => res.json()).subscribe(data=>{console.log(data}); or change subscribe to .success like if and else

  • Mainak

    Can u please help me with a HttpPost example

  • Maii Roxane

    How to do iterate through a object? I made a http request for additional information, but it only gives back an object without an array so I can’t use ngFor.

  • kalyan kumar

    Hi,
    Could you please help me to use http.post option ?. I’m facing
    “Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.” this error. Though, http.get is working fine.

    • I first need to update this article to reflect changes done to Ionic 2 in the previous several months. Though I will take me some time to do everything so my advice is to ask this question on the official Ionic forum.

      • Article (including demop example) has been updated to Ionic 2.2.1 version.

    • Developer

      That is a really hacky way to fix the issue. It really needs to be fixed serverside by setting up CORS handling.

  • Rama Astadipati

    Wow impressive tutorial, thank you.
    My I request to use our own basic api in our sites, it would be great.

    • Mompati Mokoka

      have you found anything yet please share

      • I m working on it, base express, and somehow i get a lot problem and not fixed yet

  • Sonic Wong

    Would u mine update this post to ionic v3 and Ng v4?

  • valmy roi

    This doesn’t work on ios10, as it doesn’t not allow http request

  • valmy roi

    This doesn’t work on ios10, as it doesn’t not allow http request

  • Dreamers Club

    https://uploads.disquscdn.com/images/ef1d87988c23f081fee2d0f826d160dfc829c8f2141b4cff0592b97276f3f566.png Hello! I would like to ask you what am I doing wrong here? I copied the code but it doesn’t seem to work :

  • Medz Baldono

    Can you make an article on how to call the file uploaded in php , and display it into Ionic app ? i have php file upload , my problem is i dont know how to display the file that i uploaded in php into my Ionic app

    • No problem, I will gladly write it. Could you please better describe your case? I’m not sure how is your PHP application related to your Ionic app?