Create Ionic 4/Angular 8 HTTP Service – Communicate with Server via REST API

By Digamber Rawat Last updated on
A complete step by step Ionic 4 HTTP tutorial, In this tutorial, we will learn how to create Ionic 4/Angular 8 Service using HTTP & HttpClientModule and communicate with remote server using REST API.

As we know, most of the applications render data from the remote server like YouTube has to fetch videos and display them to the users. Twitter renders tweets and shows it to its users. The same way in this tutorial i am going to show you how to build Ionic 4/Angular service to pull data from a remote server using Ionic 4 HTTP service.

We will also learn how to handle the response coming from the server in an Ionic 4/Angular app. There are two ways to handle the response returned from a web server RxJS Observables and Promise. In this tutorial we will look at both the methods and understand how to handle the response coming from web server using RxJS Observables and Promise.

Create a New Ionic 4 App

Let’s run the following command to build a new Ionic 4 app.

ionic start ionic-angular-http --type=angular

Select blank template from the Ionic 4 ready-made template list.

? Starter template: 
  tabs         | A starting project with a simple tabbed interface 
  sidemenu     | A starting project with a side menu with navigation in the content area 
❯ blank        | A blank starter project 
  my-first-app | An example application that builds a camera with gallery 
  conference   | A kitchen-sink application that shows off all Ionic has to offer

Get into the Ionic 4 Http project folder.

cd ionic-angular-http

Run the following command to install lab mode as a development dependency for testing purpose.

npm i @ionic/lab --save-dev

Start the Ionic 4 Http application by running the following command.

ionic serve -l

Ionic 4 HTTP Angular 8 Service

Register Ionic 4 HttpClientModule in AppModule

To make the HTTP requests, we must import and register HttpClientModule in app.module.ts file.

// app.module.ts 

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [...],
  entryComponents: [...],
  imports: [
    HttpClientModule
  ],
  providers: [...],
  bootstrap: [...]
})

export class AppModule { }

Create Ionic 4/Angular Service Provider

Service in Angular 8 refers to a singleton object, during the lifetime of an app it initialized only once. Angular service contains methods that help to manage the data throughout the life of an app. Angular service holds the business logic and helps in communicating with a remote server, and data can also be shared from one component to another component using Angular Dependency Injection or DI.

Create Ionic 4/Angular service by Running the following command.

ng generate service ionic-rest

Next, import IonicRestService in app.module.ts and register inside the providers array as mentioned below.

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';
import { IonicRestService } from './ionic-rest.service';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    IonicRestService
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

Check out this detailed tutorial on Building Ionic 4/Angular CRUD Mobile App.

Create Ionic 4/Angular HTTP Service with RxJS Observables

To make the HTTP request we need to import HttpClient service in ionic-rest.service.ts, It allows us to make HTTP POST, GET, PUT and DELETE requests. HttpClient requests are by-default asynchronous and we have to wait for getting the response from the server.

To set the header configuration options for HTTP Request also import HttpHeaders.

import { HttpClient, HttpHeaders } from '@angular/common/http';

Ionic 4 Handle Http Response with RxJS Observables and Operators

I assume you have a basic knowledge about RxJS Observables if not then don’t worry, RxJS Observables offers steam of data. Observables can be subscribed, and data response can easily be managed when it comes from a remote server. In this Ionic 4/Angular 8 Http tutorial, we will fetch the data from a remote origin and assign it to the observable and then subscribe the data in the Ionic page or component by using the HttpClient service.

I wrote a detailed article on Observables in Reactive Programming, check it out to know more about how does RxJS work.

RxJS Observables faster and better tool for Ionic/Angular developers to manage complex programming situations.

  • Observables deals with asynchronous operations.
  • Observables handle multiple streams of events at the same time.
  • Observables can be cancelled at any time.
  • RxJS Operators helps you to manage Observable as per your need. It offers a comprehensive list of operators such as map, tap, catchError, of etc. RxJS Observables can also be converted to promise with the help of toPromise() operator.
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

Next, Inject HttpClient in the constructor.

constructor(private http: HttpClient) { }

Let’s define a Student model in the same file above the @Injectable({…}).

export class Student {
  id: string;
  name: string;
  email: string;
  dob: number;
  fees: number;
}

Define the httpHeader inside the IonicRestService.

httpHeader = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

Next, define addStudent() method to make the Ionic 4/Angular 8 HTTP POST request to add the data in the remote server.

addStudent(student: Student): Observable<any> {
  return this.http.post<Student>('api-goes-here', student, this.httpHeader)
    .pipe(
      catchError(this.handleError<Student>('Add Student'))
    );
}

To add student, we declared the add student() method, it takes the student data as a parameter and set it to Observable. Use the http method to make the POST request, and the POST method takes three arguments. First, pass the API url, second the student’s data and third is the HttpHeader. Then, use the RxJS pipe operator to return the error, we used the handleError method if any error occurs.

Ionic 4 fetch the single item or list of items from remote server by making the HTTP call.

getStudent(id): Observable<Student[]> {
  return this.http.get<Student[]>('api-goes-here/' + id)
    .pipe(
      tap(_ => console.log(`Student fetched: ${id}`)),
      catchError(this.handleError<Student[]>(`Get student id=${id}`))
    );
}

getStudentList(): Observable<Student[]> {
  return this.http.get<Student[]>('api-goes-here/')
    .pipe(
      tap(Student => console.log('Student fetched!')),
      catchError(this.handleError<Student[]>('Get student', []))
    );
}

To fetch the data from the remote server, we define two methods getStudent(id) and getStudentList() and make them observables. We are making HTTP GET request in Ionic 4 Angular 8 service file to get the response from the server. We also used the RxJS tap() method to perform the side-effects in the Angular 8 service methods.

Final code of Ionic 4/Angular 8 Service to handle HTTP requests in ionic-rest.service.ts file.

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';

export class Student {
  id: string;
  name: string;
  email: string;
  dob: number;
  fees: number;
}

@Injectable({
  providedIn: 'root'
})

export class IonicRestService {

  httpHeader = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };

  constructor(private http: HttpClient) { }

  addStudent(student: Student): Observable<any> {
    return this.http.post<Student>('api-goes-here/', student, this.httpHeader)
      .pipe(
        catchError(this.handleError<Student>('Add Student'))
      );
  }

  getStudent(id): Observable<Student[]> {
    return this.http.get<Student[]>('api-goes-here/' + id)
      .pipe(
        tap(_ => console.log(`Student fetched: ${id}`)),
        catchError(this.handleError<Student[]>(`Get student id=${id}`))
      );
  }

  getStudentList(): Observable<Student[]> {
    return this.http.get<Student[]>('api-goes-here/')
      .pipe(
        tap(Student => console.log('Student fetched!')),
        catchError(this.handleError<Student[]>('Get student', []))
      );
  }

  updateStudent(id, student: Student): Observable<any> {
    return this.http.put('api-goes-here/' + id, student, this.httpHeader)
      .pipe(
        tap(_ => console.log(`Student updated: ${id}`)),
        catchError(this.handleError<Student[]>('Update student'))
      );
  }

  deleteStudent(id): Observable<Student[]> {
    return this.http.delete<Student[]>('api-goes-here/' + id, this.httpHeader)
      .pipe(
        tap(_ => console.log(`Student deleted: ${id}`)),
        catchError(this.handleError<Student[]>('Delete student'))
      );
  }


  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);
      console.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    };
  }
}

Handle Ionic 4/Angular 8 HTTP Response with Promise

The Promise object in JavaScript is the value which hasn’t been available yet but will be available in the future. It helps you convert asynchronous code into synchronous manner.

Promises in ECMAScript are very much similar to the promises we make in day to day life. JavaScript Promise is a guarantee to do or not do something.

A promise has three states:

  • pending: Initial state before called or rejection.
  • fulfilled: promise has completed with a value.
  • rejected: When the operation gets failed.

Promise Syntax

const myPromise = new Promise((resolve, reject) => {
  // perform asynchronous task which might either be:
  //
  //   resolve(myVal); // fulfilled
  // or
  //   reject("failed with message"); // rejected
});

To handle the HTTP GET response we are using the JavaScript Promise method in Ionic 4/Angular app.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

class PostObj {
  constructor(
    public userId: number,
    public id: string,
    public title: string,
    public body: string
  ) { }
}

@Injectable({
  providedIn: 'root'
})

export class IonicRestService {

  restAPI: string = "https://jsonplaceholder.typicode.com/posts";
  postData = [];

  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.fetchPosts();
  }

  fetchPosts() {
    const promise = new Promise((resolve, reject) => {
      const URL = this.restAPI;
      this.http
        .get<PostObj[]>(URL)
        .toPromise()
        .then((res: any) => {
          this.postData = res.map((res: any) => {
            return new PostObj(
              res.userId,
              res.id,
              res.title,
              res.body
            );
          });
          resolve();
        },
          err => {
            reject(err);
          }
        );
    });
    return promise;
  }
}

Conclusion

Finally, we have completed Ionic 4/Angular 8 HTTP Service tutorial. In this tutorial we learned how to create Angular service in Ionic 4 app to communicate with the remote server via REST APIs.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Thanks for checking this tutorial out :) Let me know if you have any suggestions or issue related to this tutorial, or you want to request a new tutorial. Just shoot me a mail here.