Create HTTP Service in Ionic 7 Angular Application

Last Updated on by in Ionic
A comprehensive Ionic HTTP Requests tutorial, In this tutorial, we will learn how to create Ionic Angular 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. For instance YouTube fetches videos and display them to the users. Twitter renders tweets and shows it to its users.

In the same way in this tutorial we wre going to show you how to build service in Ionic Angular to pull data from a remote server using HTTP Requests through the Angular service.

We will also learn how to handle the response coming from the server in an Ionic/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 App

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

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

Get inside the project.

cd ionic-angular-http

Run the below command to add the native core package.

npm install @ionic-native/core --legacy-peer-deps

Disable Strict Type Errors

To avoid TypeScript compiling issues, we just need to open tsconfig.json file:

First, set below property under “compilerOptions” property.

"compilerOptions": {
    "strictPropertyInitialization": false,
    "skipLibCheck": true
    ...
}

Secondly, add given props under “angularCompilerOptions”.

"angularCompilerOptions": {
    "strictTemplates": false,
    ...
}

Register Ionic HttpClientModule in AppModule

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

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

@NgModule({
  imports: [
    HttpClientModule,
  ],
})

Create Ionic/Angular Service Provider

Service in Angular 16 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/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 { 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],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    HttpClientModule,
  ],
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    IonicRestService,
  ],
  bootstrap: [AppComponent],
})

export class AppModule {}

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

Create 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 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 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;
  username: string;
  email: string;
  phone: number;
}

Define the httpHeader inside the IonicRestService.

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

Next, define addStudent() method to make the Ionic 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 fetch the single item or list of items from remote server by making the HTTP call.

getStudent(id: any): 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 service file to get the response from the server.

We also used the RxJS tap() method to perform the side-effects in the Angular 16 service methods.

Final code of Ionic 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;
  username: string;
  email: string;
  phone: number;
}

@Injectable({
  providedIn: 'root',
})
export class IonicRestService {
  URL: string = 'https://jsonplaceholder.typicode.com/users';

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

  constructor(private http: HttpClient) {}

  addStudent(student: Student): Observable<any> {
    return this.http
      .post<Student>(`${URL}/`, student, this.httpHeader)
      .pipe(catchError(this.handleError<Student>('Add Student')));
  }

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

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

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

  deleteStudent(id: any): Observable<Student[]> {
    return this.http.delete<Student[]>(`${URL}/` + 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);
    };
  }
}

Head over to the app.componenet.html file; here in this file we will fetch the data from the server and show the observable data.

import { Component } from '@angular/core';
import { IonicRestService } from './ionic-rest.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})

export class AppComponent {
  constructor(private ionicRestService: IonicRestService) {}

  ngOnInit(): void {
    this.ionicRestService.getStudentList().subscribe((data) => {
      console.log(data);
    });
  }
}

Ionic Angular Observable HTTP Request Example

Handle HTTP Response with Promise in Ionic

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

Insert given code into the ionic-rest.service.ts file:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { lastValueFrom, take } from 'rxjs';

export class PostObj {
  userId: number;
  title: string;
  body: string;
}

@Injectable({
  providedIn: 'root',
})

export class IonicRestService {
  URL: string = 'https://jsonplaceholder.typicode.com/posts';
  postData = [];

  constructor(private httpClient: HttpClient) {}

  async fetchPosts(): Promise<any> {
    let request = this.httpClient.get(this.URL).pipe(take(2));

    return await lastValueFrom<any>(request);
  }
}

Add below code within the app.component.ts file:

import { Component } from '@angular/core';
import { IonicRestService } from './ionic-rest.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})

export class AppComponent {
  constructor(private ionicRestService: IonicRestService) {}

  ngOnInit() {
    this.ionicRestService.fetchPosts().then((res) => {
      console.log(res)
    })
  }
}

Handle HTTP Response with Promise in Ionic

Conclusion

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

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.