Ionic 4 | Making REST HTTP Requests Like a Pro

Written by on June 14, 2019

Ionic 4 | Making REST HTTP Requests Like a Pro

Source Code

In case GitHub repo is not available, and you can only use a code provided below. This is what the project folder looks like:

app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
list.page.html
    
<ion-header>
  <ion-toolbar>
    <ion-title>List Page</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
    <ion-item>
        <ion-label color="primary" stacked>Search movie database</ion-label>
        <ion-input type="text" (input)="searchForMovie($event, searchKey)"></ion-input>
    </ion-item>
 
    <ion-list>    
        <ion-item *ngFor="let movie of movies" (click)="selectMovie($event, movie)">
			<ion-thumbnail slot="start">
				<img src="https://image.tmdb.org/t/p/w92{{movie.poster_path}}">
			</ion-thumbnail>
			<ion-label>
				<h2>{{movie.original_title}}</h2>
				<p>{{movie.overview}}</p>
			</ion-label>
        </ion-item>
    </ion-list>   
</ion-content>
list.page.ts
import { Component, OnInit } from '@angular/core';
import { MovieServiceService } from '../../services/movie-service.service';
import { InfoPage } from '../info/info.page';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';

@Component({
  selector: 'app-list',
  templateUrl: './list.page.html',
  styleUrls: ['./list.page.scss'],
})
export class ListPage {

    movies: any[];
 
    constructor(private movieService: MovieServiceService, private router: Router) {
 
    }
 
    searchForMovie(event, key) {
        if(event.target.value.length > 2) {
		    this.movieService.searchMovies(event.target.value).subscribe((res)=>{
		    	this.movies = res;
		    });
        }
    }  
     
    selectMovie(event, movie) {
        console.log(movie);
        this.router.navigateByUrl('/info/' + movie.id);
    }
}
movie-service.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Movies } from '../services/movies';

@Injectable({
  providedIn: 'root'
})
export class MovieServiceService {
 
	apiURL: string = 'http://api.themoviedb.org/3/search/movie?query=&query=';
	apiKey: string = 'api_key=5fbddf6b517048e25bc3ac1bbeafb919';
	movies: any = [];

	constructor(private http: HttpClient) { 

	}

	searchMovies(movieName: string) {
		return this.http.get<any>(`${this.apiURL}` + encodeURI(movieName) + `&${this.apiKey}`).pipe(
    		map(model => {
    				this.movies = model.results;
		      		return model.results;
    			}
    		)
    	);	
	}

	getMovieFromCache(id: string) {
		let cachedMovie = null;

	    this.movies.forEach(movie => {
			if (movie.id == id) {
				cachedMovie = movie;
	      	}
	    });

	    console.log(cachedMovie);

	    return cachedMovie;
	}
}
info.page.html
<ion-header>
	<ion-toolbar>
		<ion-buttons slot="start">
		  	<ion-back-button></ion-back-button>
		</ion-buttons>  	
		<ion-title>Info Page</ion-title>
	</ion-toolbar>
</ion-header>

<ion-content>
	<ion-card *ngIf="movie">
		<img src="https://image.tmdb.org/t/p/w92{{movie.poster_path}}"/>
		<ion-card-header>
			<ion-card-subtitle>{{movie.release_date}}</ion-card-subtitle>
			<ion-card-title>{{movie.title}}</ion-card-title>
		</ion-card-header>

		<ion-card-content>{{movie.overview}}</ion-card-content>
	</ion-card>
</ion-content>
info.page.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MovieServiceService } from '../../services/movie-service.service';

@Component({
  selector: 'app-info',
  templateUrl: './info.page.html',
  styleUrls: ['./info.page.scss'],
})
export class InfoPage implements OnInit {

	id: string;
	movie: {};

  	constructor(private movieService: MovieServiceService, private route: ActivatedRoute) { }

	ngOnInit() {
		this.id = this.route.snapshot.paramMap.get('id');
		this.movie = this.movieService.getMovieFromCache(this.id);
	}

}

Deployment

Next step, build our application:

ionic build android

or

ionic build browser

Be careful here, this step may break if you’re behind a firewall. The first execution will take a long time, so be patient.

Finally:

ionic run android -l -c -s

or

ionic run browser -l -c -s

or if you want to test it in your browser:

ionic serve

Download The Code

Working GitHub repo link can be found below:

GitHub

Here's a Way You Can Support Us And Benefit at the Same Time

If this article helped you here’s one thing you can do for me. While writing articles I’m using Notion tool for information gathering. It’s a modern alternative to Evernote. If you use Evernote or any similar application give also a chance to Notion. By signing up, you will get access to a very powerful tool, give me one more premium month, and in turn help me to write future articles.

More Ionic 4 Tutorials

Categories

37 thoughts on “Ionic 4 | Making REST HTTP Requests Like a Pro”

  1. 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.

  2. 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.

    • 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.

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

    • 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.

    • 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]];
      }

  4. 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.

    • 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

  5. 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.

  6. 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.

    • 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

  7. 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.

  8. 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.

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

  10. 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

  11. Im trying to build the apk for Android and i get this error:

    Typescript error
                
    Type InfoPage in E://IonicHTTPRestExample/src/pages/info/info.ts is part of the declarations of 2 modules: 
    
    AppModule in E://IonicHTTPRestExample/src/app/app.module.ts and InfoPageModule in E://IonicHTTPRestExample/src/pages/info/info.module.ts
    
    Please consider moving InfoPage in E://IonicHTTPRestExample/src/pages/info/info.ts to a higher module that imports AppModule in E://IonicHTTPRestExample/src/app/app.module.ts and InfoPageModule in
    E://IonicHTTPRestExample/src/pages/info/info.module.ts
    
    You can also create a new NgModule that exports and includes InfoPage in E://IonicHTTPRestExample/src/pages/info/info.ts then import that NgModule in AppModule in E://IonicHTTPRestExample/src/app/app.module.ts and InfoPageModule in E://IonicHTTPRestExample/src/pages/info/info.module.ts

    I revised all the code and is the same as Github, i don’t understand how to fix this :/, any idea?

Leave a Reply