Getting Started

Summary: This post aims to simplified consuming REST API on Ionic 3 mobile apps using the new Angular 4.3 HttpClient. You can compare this new way of accessing or consuming REST API with the previous way on Angular Versions. Still the same with the previous tutori

Step 1# Install or update Ionic  using this command: 

sudo npm install -g ionic

Step 2# Create ionic app :

As usual, we are creating new Ionic  app from scratch. Open the terminal or Node command line then type this command.

ionic start ionic3-angular43-rest blank
cd ionic3-angular43-rest
ionic serve --lab

To make sure everything working properly run the app in labs mode, it will open automatically in the browser.
ionic serve --lab

Step 3# For safe use with Ionic 3, update all '@angular' dependencies with the latest version and install all missing dependencies.

npm install @angular/common@latest --save
npm install @angular/compiler@latest --save
npm install @angular/compiler-cli@latest --save
npm install @angular/core@latest --save
npm install @angular/forms@latest --save
npm install @angular/http@latest --save
npm install @angular/platform-browser@latest --save
npm install @angular/platform-browser-dynamic@latest --save

Step 4# Next, open and edit 'src/app/app.module.ts' then add this import.

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

Then register it to '@NgModule' imports after 'BrowserModule', so it will look like this.

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

Step 5#  This time we will implement the new Angular 4.3 HTTPClient on the Ionic 3 service or provider. Create the service or provider file by type this command.

ionic g provider Rest

It will create 'rest.ts' file and 'rest' folder inside 'providers' folder and also register it on 'app.module.ts'. Now, open and edit 'providers/rest/rest.ts' then replace 'http' import by new Angular 4.3 HTTPClient.

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

Also, replace 'Http' injection in the constructor.

constructor(public http: HttpClient) {
  console.log('Hello RestServiceProvider Provider');
}

Next, we will create all REST API call inside 'rest.ts' file. Add this line before the constructor.

apiUrl = 'https://jsonplaceholder.typicode.com';

Add this functions after constructors.

getUsers() {
  return new Promise(resolve => {
    this.http.get(this.apiUrl+'/users').subscribe(data => {
      resolve(data);
    }, err => {
      console.log(err);
    });
  });
}

You can see the difference in getting data more simple than using the previous HTTP and it also added retry function if something happens with the request. Now, add again function to post new data.

addUser(data) {
  return new Promise((resolve, reject) => {
    this.http.post(this.apiUrl+'/users', JSON.stringify(data))
      .subscribe(res => {
        resolve(res);
      }, (err) => {
        reject(err);
      });
  });
}

For posting data,

this.http.post(this.apiUrl+'/users', JSON.stringify(data), {
    headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
    params: new HttpParams().set('id', '3'),
  })
  .subscribe(res => {
    resolve(res);
  }, (err) => {
    reject(err);
  });

Step 6# To displaying data in the view, open and edit `src/pages/home/home.ts` then add this import.

import { RestProvider } from '../../providers/rest/rest';constructor(public navCtrl: NavController, public restProvider: RestProvider) {}

Create a function below the constructor for calling the users from the provider then fill users variable.

getUsers() {
    this.restProvider.getUsers()
    .then(data => {
      this.users = data;
      console.log(this.users);
    });
  }

Now, call that function inside the constructor.

constructor(public navCtrl: NavController, public restProvider: RestProvider) {
    this.getUsers();
  }

Then, open and edit 'src/pages/home/home.html' then replace '<ion-content>' and it's content using this.

<ion-content>
  <ion-list inset>
    <ion-item *ngFor="let user of users">
      <h2>{{user.name}}</h2>
      <p>{{user.email}}</p>
    </ion-item>
  </ion-list>
</ion-content>

 


If you like it you can donate :)

share

Comments

Sign in to publish a comment

0 comments

Be the first to comment on this post.