61

Ionic 4 Angular 6 Tutorial: Call Multiple Services at Once

 5 years ago
source link: https://www.tuicool.com/articles/hit/I7bA3u
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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` which should be load perfectly for all HTTP calls. There will a problem when we show `LoadingController` for each service calls separately because it will load asynchronously. So, you will be facing this kind of error.

ERROR Error: Uncaught (in promise): removeView was not found
    at c (polyfills.js:3)
    at c (polyfills.js:3)
    at polyfills.js:3
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4751)
    at t.invokeTask (polyfills.js:3)
    at r.runTask (polyfills.js:3)
    at o (polyfills.js:3)

Table of Contents:

  • Ionic 4 and Angular 6 Tutorial: Create a New App
  • Ionic 4 and Angular 6 Tutorial: Create Service for Accessing RESTful API
  • Ionic 4 and Angular 6 Tutorial: View Data in the Home Page
  • Ionic 4 and Angular 6 Tutorial: Test and Run the Ionic 4 and Angular 6 App

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

1. Ionic 4 and Angular 6 Tutorial: Create a New App

To create a new Ionic 4 / Angular 6 app, 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 asking to install `@ionic/lab`. Now, the browser will open automatically then you will see this Ionic 4 Lab page.

QFfAnmZ.png!web

2. Ionic 4 and Angular 6 Tutorial: Create Service for Accessing RESTful API

To separate the presentation data from data access, we have to create a service for accessing RESTful 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.

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

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

Add constant variable that contain of API URL before the `@Injectable` annotation.

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

Next, inject `HttpClient` to the constructor params.

constructor(private http: HttpClient) { }

Add the functions for handle error and extract response data.

private handleError(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
    console.error('An error occurred:', error.error.message);
  } else {
    // The backend returned an unsuccessful response code.
    // The response body may contain clues as to what went wrong,
    console.error(
      `Backend returned code ${error.status}, ` +
      `body was: ${error.error}`);
  }
  // return an observable with a user-facing error message
  return throwError('Something bad happened; please try again later.');
}

private extractData(res: Response) {
  let body = res;
  return body || { };
}

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

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

3. Ionic 4 and Angular 6 Tutorial: View Data in the Home Page

We will put the multiple country Post Code data in the existing home page. To view data from multiple RESTful API calls that previously handles by the service, open and edits `src/app/home/home.page.ts` then add this imports.

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();
  await 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-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>

4. Ionic 4 and Angular 6 Tutorial: 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.

q263iqy.png!web

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 Ion2FullApp ELITE - The Complete Ionic 3 Starter App and save development and design time.

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

Or take the following course:

Thanks


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK