Example of Ionic 3 Angular 4 Cordova Barcode and QR Code Scanner

by Didin J. on Sep 15, 2017 Example of Ionic 3 Angular 4 Cordova Barcode and QR Code Scanner

An example of creating Ionic 3 Angular 4 Cordova Barcode and QR Code Scanner using Ionic 3 Native Barcode Scanner.

This tutorial shows you how to create an example of Ionic 3, Angular 4 and Cordova Barcode and QR code Scanner using Ionic 3 Native Barcode Scanner. Actually, there is an Ionic 3 QR Scanner plugin, but we decide to use this Barcode plugin that can scan both Barcode and QR code. This barcode and QR code scanner example is price checker app. So, the app will use local JSON data to get a price by barcode or QR code number. Here's the app flow.

Example of Ionic 3 Angular 4 Cordova Barcode and QRCode Scanner - App Flow

The following tools, modules, and dependencies should prepare before starting the tutorial:

- Node.js (Stable or recommended version)
- Latest Ionic 3, Angular 4 and Cordova
- Ionic Native Barcode Scanner Plugin
- Ionic Native Toast Plugin
- Terminal or Command Line
- Text Editor or IDE
- Android or iOS device

We assume that you have installed Node.js and able to run `npm` in Node.js command line (Windows) or Terminal (OS X/Linux). To make sure everything is up to date, type this command in the terminal or Node command line.

npm install -g ionic cordova

Sometimes on OS X terminal need `sudo` for that command.


1. Create a new Ionic 3 and Angular 4 App

As usual, we start tutorial from scratch or from zero. In the terminal or Node command line type this command to create a new Ionic 3 and Angular 4 app. Make sure you are in your projects folder.

ionic start ionic3-barcode blank

Go to the newly created app folder.

cd ionic3-barcode

Run the app for the browser to make sure everything working properly by type this command.

ionic serve --lab

If you see this page in your browser then you are ready to move.

Example of Ionic 3 Angular 4 Cordova Barcode and QRCode Scanner - Ionic 3 Home


2. Add and Configure Ionic 3 Native Barcode and Toast Plugin

To add Ionic 3 Native Barcode and Toast plugin, just type this commands.

ionic cordova plugin add phonegap-plugin-barcodescanner
npm install --save @ionic-native/barcode-scanner
ionic cordova plugin add cordova-plugin-x-toast
npm install --save @ionic-native/toast

Now, open and edit `src/app/app.module.ts` then add this imports.

import { BarcodeScanner } from '@ionic-native/barcode-scanner';
import { Toast } from '@ionic-native/toast';

Add `BarcodeScanner` and `Toast` to `@NgModule` providers, so it will look like this.

providers: [
  StatusBar,
  SplashScreen,
  {provide: ErrorHandler, useClass: IonicErrorHandler},
  BarcodeScanner,
  Toast
]


3. Implement Ionic 3 Barcode or QR code scanner

Before implementing Ionic 3 Barcode or QR code scanner on view and controller, first we have to make a JSON file for product data. Create a new folder inside `src/assets` by type this command.

mkdir src/assets/data

Inside that new folder create a new JSON file.

touch src/assets/data/products.json

Now, fill the JSON file with single data like this.

[
  {
    "plu":"01234567895",
    "name":"Gaming DDR5 RAM 16GB",
    "price":76,
    "desc":"Gaming DDR5 RAM 16GB PC-128000 For x64 PC"
  },
  {
    "plu":"01234567898",
    "name":"Intel Core i7 3.3GHz",
    "price":200,
    "desc":"Intel Core i7 3.3GHz L2 16MB 4.6ns"
  }
]

Next, create a service or provider for accessing the JSON data by typing this command.

ionic g provider DataService

Open and edit `src/providers/data-service/data-service.ts` then add this function after constructor.

getListDetails(){
  return this.http.get('assets/data/products.json')
    .map((response:Response)=>response.json());
}

Don't forget to register `HttpModule` in `src/app/app.module.ts` by add this import.

import { HttpModule } from '@angular/http';

And declare this `HttpModule` in `@NgModule` imports.

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

Now, open and edit `src/pages/home/home.ts` then add this import.

import { BarcodeScanner } from '@ionic-native/barcode-scanner';
import { Toast } from '@ionic-native/toast';
import { DataServiceProvider } from '../../providers/data-service/data-service';

And inject all of that imports to the constructor.

constructor(public navCtrl: NavController,
  private barcodeScanner: BarcodeScanner,
  private toast: Toast,
  public dataService: DataServiceProvider) {}

Declare this variables before the constructor.

products: any[] = [];
selectedProduct: any;
productFound:boolean = false;

Add this function for get JSON data inside constructor body.

this.dataService.getProducts()
  .subscribe((response)=> {
      this.products = response
      console.log(this.products);
  });

Create a new function for scan barcode or QRCode.

scan() {
  this.selectedProduct = {};
  this.barcodeScanner.scan().then((barcodeData) => {
    this.selectedProduct = this.products.find(product => product.plu === barcodeData.text);
    if(this.selectedProduct !== undefined) {
      this.productFound = true;
    } else {
      this.productFound = false;
      this.toast.show(`Product not found`, '5000', 'center').subscribe(
        toast => {
          console.log(toast);
        }
      );
    }
  }, (err) => {
    this.toast.show(err, '5000', 'center').subscribe(
      toast => {
        console.log(toast);
      }
    );
  });
}

Now, open and edit `src/pages/home/home.html` then add this lines to `<ion-content>`.

<h1>
  <button ion-button color="dark" full round (click)="scan()">Start Scan</button>
</h1>

<ion-card *ngIf="productFound">
  <ion-card-header>
    <h2>Price: $ {{selectedProduct.price}}</h2>
  </ion-card-header>
  <ion-card-content>
    <ul>
      <li>{{selectedProduct.plu}}</li>
      <li>{{selectedProduct.name}}</li>
      <li>{{selectedProduct.desc}}</li>
    </ul>
  </ion-card-content>
</ion-card>


4. Test the Ionic 3 Barcode/QRCode Scanner App on the Real Device

Before test on the real devices make sure you have connected your Android/iOS device to your Computer. For safety, add remove Ionic Cordova Android/iOS platform.

ionic cordova platform rm android
ionic cordova platform add android
ionic cordova platform rm ios
ionic cordova platform add ios

Now, run on your Android/iOS device.

ionic cordova run android

or

ionic cordova run ios

You will land on this page.

Example of Ionic 3 Angular 4 Cordova Barcode and QRCode Scanner - Scanner Page

Go to online barcode generator or QR code generator to create your barcode or QR code then scan it. If found you see the product price and details below the scan button.

Example of Ionic 3 Angular 4 Cordova Barcode and QRCode Scanner - Barcode Match with Product

Otherwise, you will see Toast with `Not found` message.

That it's, please leave your comment, suggestion or critics below. You can find the working source code on our GitHub.

Thanks!

The following resources might be useful for you:

Loading…