Ionic 4 Angular 6 Tutorial: Call Multiple Services at Once

by Didin J. on Sep 09, 2018 Ionic 4 Angular 6 Tutorial: Call Multiple Services at Once

A comprehensive step by step tutorial on calling multiple services at once using Ionic 4, Angular 6 and RXJS Observable forkJoin

A comprehensive step by step tutorial on calling multiple services at once using Ionic 4, Angular 6 and RXJS Observable `forkJoin`. Today we have a case when we need to call multiple services (HTTP call) on the same page or component. On that page, we also put a `LoadingController` once for all HTTP calls.  Sometimes, we need to calls multiple services that call different API URL a once synchronously. For that, this method for Ionic 4 and Angular 6 is one of the effective methods to do that.


Table of Contents:


The following tools, frameworks, and modules are required for this tutorial:

Before moving to the steps, make sure you have installed the latest Node.js and Ionic 4. To check it, type this command in the terminal or Node.js command line.

node -v
v8.11.4
npm -v
5.6.0
ionic -v
ionic CLI 4.1.2
cordova -v
8.0.0


Create a New Ionic 4 Angular 6 App

To create a new Ionic 4 / Angular 6 app with the name ionic-forkjoin, type this command.

ionic start ionic-forkjoin blank --type=angular

You will see questions during the installation, just type `N` for now. Next, go to the newly created app folder.

cd ./ionic-forkjoin

For sanitizing, run the app on the browser for the first time to make sure everything working properly.

ionic serve -l

Type `Y` if asked to install `@ionic/lab`. Now, the browser will open automatically then you will see this Ionic 4 Lab page.

Ionic 4 Angular 6 Tutorial: Call Multiple Services at Once - Ionic Home Page


Create Ionic Service for Accessing REST API

To separate the presentation data from data access, we have to create a service for accessing the REST API from our server.

ionic g service rest-api

Before modifying the service file, open and edit `src/app/app.module.ts` then add this import of HttpClientModule that part of @angular/common/http.

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

Then add this module to the `@NgModule` imports.

imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule,],

Next, open and edit `src/app/rest-api.service.ts` then add these imports of RxJS Observable, of, throwError, @angular/common/http HttpClient, HttpHeaders, HttpErrorResponse, and RxJS forkJoin.

import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { forkJoin } from 'rxjs';

Add a constant variable that contains API URL (we are using free API of ZIP CODE) before the `@Injectable` annotation.

const apiUrl = "http://api.zippopotam.us/";

Next, inject `HttpClient` to the constructor params.

constructor(private http: HttpClient) { }

Next, create multiple REST API service calls at once in a function.

getData(): Observable<any> {
  let response1 = this.http.get(apiUrl+'US/00210');
  let response2= this.http.get(apiUrl+'IN/110001');
  let response3 = this.http.get(apiUrl+'BR/01000-000');
  let response4 = this.http.get(apiUrl+'FR/01000');
  return forkJoin([response1, response2, response3, response4]);
}


View Data in the Ionic Home Page

We will put the multiple country Post Code data in the existing home page. To view data from multiple REST API calls that previously handled by the service, open and edits `src/app/home/home.page.ts` then add these imports of @ionic/angular LoadingController and RestApiService.

import { LoadingController } from '@ionic/angular';
import { RestApiService } from '../rest-api.service';

Inject the `RestApiService` and `LoadingController` to the constructor params.

constructor(public api: RestApiService, public loadingController: LoadingController) { }

Add these variables before the constructor for holding all response from the API calls.

data1: any;
data2: any;
data3: any;
data4: any;

Add this function to call the service.

async getData() {
  const loading = await this.loadingController.create({
    message: 'Loading'
  });
  await loading.present();
  this.api.getData()
    .subscribe(res => {
      console.log(res);
      this.data1 = res[0];
      this.data2 = res[1];
      this.data3 = res[2];
      this.data4 = res[3];
      loading.dismiss();
    }, err => {
      console.log(err);
      loading.dismiss();
    });
}

In the Angular 6 `ngOnInit` lifecycle hooks call that function.

ngOnInit() {
  this.getData();
}

Next, open and edit `src/app/home/home.page.html` then replace all HTML 5 tags with this <ion-card>, <ion-card-header>, <ion-card-content> that contains an iteration of multiple array of data.

<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <ion-card>
    <ion-card-header>
      <ion-card-subtitle>{{data1['country']}}</ion-card-subtitle>
      <ion-card-title>{{data1['post code']}}</ion-card-title>
    </ion-card-header>

    <ion-card-content>
      <ul>
        <li *ngFor="let p of data1.places">{{p['place name']}}</li>
      </ul>
    </ion-card-content>
  </ion-card>
  <ion-card>
    <ion-card-header>
      <ion-card-subtitle>{{data2['country']}}</ion-card-subtitle>
      <ion-card-title>{{data2['post code']}}</ion-card-title>
    </ion-card-header>

    <ion-card-content>
      <ul>
        <li *ngFor="let p of data2.places">{{p['place name']}}</li>
      </ul>
    </ion-card-content>
  </ion-card>
  <ion-card>
    <ion-card-header>
      <ion-card-subtitle>{{data3['country']}}</ion-card-subtitle>
      <ion-card-title>{{data3['post code']}}</ion-card-title>
    </ion-card-header>

    <ion-card-content>
      <ul>
        <li *ngFor="let p of data3.places">{{p['place name']}}</li>
      </ul>
    </ion-card-content>
  </ion-card>
  <ion-card>
    <ion-card-header>
      <ion-card-subtitle>{{data4['country']}}</ion-card-subtitle>
      <ion-card-title>{{data4['post code']}}</ion-card-title>
    </ion-card-header>

    <ion-card-content>
      <ul>
        <li *ngFor="let p of data4.places">{{p['place name']}}</li>
      </ul>
    </ion-card-content>
  </ion-card>
</ion-content>


Test and Run the Ionic 4 and Angular 6 App

Now you can test the Ionic 4 and Angular 6 App by type this command.

ionic serve -l

You see in the browser the change of the home page.

Ionic 4 Angular 6 Tutorial: Call Multiple Services at Once - Run the App

As you can see, the `Loading Controller` run smoothly.

That it's, the Ionic 4 Angular 6 Tutorial: Call Multiple Services at Once. You can get the full working source code in our GitHub.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ionic 4 - Full Starter App and save development and design time. Android, iOS, and PWA, 100+ Screens and Components, the most complete and advance Ionic Template.

That just the basic. If you need more deep learning about Ionic, Angular, and Typescript, you can take the following cheap course:

Thanks

Loading…