Ionic 5 Tutorial: Create Offline Price Checker (Angular 9)

栏目: IT技术 · 发布时间: 6年前

内容简介:In this Ionic 5 tutorial, we will create an offline price checker using SQLite, Barcode Scanner, and Angular 9. The price checker usually uses by the store or retail business to check the actual price of the item, product, or goods. So, inside this app wil

In this Ionic 5 tutorial, we will create an offline price checker using SQLite, Barcode Scanner, and Angular 9. The price checker usually uses by the store or retail business to check the actual price of the item, product, or goods. So, inside this app will contain an SQLite database table of products that have fields id, price look-up (PLU) or product code, barcode, product name, product description, and product sell price.

This tutorial divided into several steps:

  • Step #1: Create a New Ionic 5 App with Angular 9 Type
  • Step #2: Install and Configure the Required Plugin/Libraries
  • Step #3: Implementing Price Checker
  • Step #4: Run and Test the Ionic 5 Price Checker App on Device

The table of the SQLite looks like this:

Ionic 5 Tutorial: Create Offline Price Checker (Angular 9)

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

  1. Node.js (Stable or recommended version)
  2. Latest Ionic 5, Angular 9 and Capacitor
  3. Ionic Native SQLite Plugin
  4. Ionic Native Barcode Scanner Plugin
  5. Terminal or Command Line
  6. Text Editor or IDE
  7. Android or iOS device

Let's get started with the main steps!

Step #1: Create a New Ionic 5 App with Angular 9 Type

We will use Ionic CLI to create a new Ionic 5 app. For that, we need to install or update the Ionic CLI to the latest version. Before that, make sure you have to install Node.js and NPM. To check the installed Node.js and NPM, type these commands from the Terminal or Node command line.

node -v
v12.18.0
npm -v
6.14.5

That's the version that we are currently using right now. To install or update Ionic CLI, type this command.

sudo npm install -g @ionic/cli

Sudo is optional is your Node.js/NPM requires administrator permission. Now, we have this version of Ionic CLI 6.

ionic -v
6.10.1

Next, create a new Ionic 5 app by type this command.

ionic start pricechecker blank

Select Angular as the framework for this Ionic app then integrate with Capacitor by choosing "Y" because we will use a Capacitor to build this Price Checker app to mobile device/simulator. If you get this error during NPM modules installation.

 Unexpected end of JSON input while parsing near '...openpgpjs.org\r\n\r\n'

Just run this NPM command then run again NPM installation.

cd ./pricechecker
npm cache clean --force
npm install

Next, run this new Ionic 5 app for the first time.

ionic serve -l

If there's a question to install @ionic/lab, just type "Y" to install it. If your browser opens this Ionic 5 app automatically and shows a blank Ionic app then your Ionic 5 app is ready to develop.

Ionic 5 Tutorial: Create Offline Price Checker (Angular 9)

Step #2: Install and Configure the Required Plugin/Libraries

As we mention in the first paragraph of this tutorial, we will use the Ionic Native Barcode plugin for scanning the product barcode and Ionic Native SQLite plugin to get product data. To install those plugins, type these commands.

npm install cordova-sqlite-storage
npm install @ionic-native/sqlite
npm install phonegap-plugin-barcodescanner
npm install @ionic-native/barcode-scanner
ionic cap sync

Next, open and edit "src/app/app.module.ts" then add these imports.

import { BarcodeScanner } from '@ionic-native/barcode-scanner/ngx';
import { SQLite } from '@ionic-native/sqlite/ngx';

Add those modules to @NgModule providers.

  providers: [
    ...
    BarcodeScanner,
    SQLite
  ],

Next, add a function that creates an SQLite table and the dummy data to the SQLite by that contain PLU, barcode number, product name, product description, and price. For this example, we are using a real-world product that has a barcode on it.

  populateTable() {
    this.sqlite.create({
      name: 'pricechecker.db',
      location: 'default'
    }).then((db: SQLiteObject) => {
      // tslint:disable-next-line: max-line-length
      db.executeSql('CREATE TABLE IF NOT EXISTS product(id INTEGER PRIMARY KEY, plu TEXT, barcode TEXT, prodname TEXT, proddesc TEXT, price INT)', [])
      .then(res => console.log('Table created'))
      .catch(e => console.log(e));
      db.executeSql('SELECT * FROM product ORDER BY rowid DESC', [])
      .then(res => {
        if (res.rows.length === 0) {
          db.executeSql('INSERT INTO product VALUES (NULL, ?, ?, ?, ?, ?)', ['10001', '8998838350058', 'Kenko Stapler', 'Kenko Stapler HD-10D blue color', 1.2]);
          db.executeSql('INSERT INTO product VALUES (NULL, ?, ?, ?, ?, ?)', ['10002', '6935205316790', 'Deli Correction Fluid', 'Deli Correction Fluid 18ml metal trip and brush', 0.89]);
          db.executeSql('INSERT INTO product VALUES (NULL, ?, ?, ?, ?, ?)', ['10003', '8718696701959', 'Philips LED Bulb 10.5W', 'Philips LED Bulb 10.5W 1055 lumen Comfortable Brightness', 3.99]);
        }
      });
    }).catch(e => console.log(e));
  }

As you can see, we just insert data to the SQLite table only if there's no data in the table. Call that function inside the constructor body.

  constructor(
    ...
  ) {
    ...
    this.populateTable();
  }

Now, the Ionic Native SQLite and Barcode plugin is ready to use.

Step #3: Implementing Price Checker

We will use two ways of checking the product price. They are by scanning the barcode then match the existing product in the SQLite table and by type the product code in the input text. Open and edit "src/app/home/home.page.ts" then add these imports of SQLite and the BarcodeScanner.

import { SQLite, SQLiteObject } from '@ionic-native/sqlite/ngx';
import { BarcodeScanner } from '@ionic-native/barcode-scanner/ngx';

Declare the following variables at the top of the class body.

  plu = '';
  barcode = '';
  name = '';
  description = '';
  price = null;
  productnumber = '';

Inject the imported modules to the constructor.

  constructor(
    private barcodeScanner: BarcodeScanner,
    private sqlite: SQLite
  ) {}

Add a function to run BarcodeScanner and send the scanned barcode text to the matchProduct() function.

  scanBarcode() {
    this.barcodeScanner.scan().then(barcodeData => {
      console.log('Barcode data', barcodeData);
      this.matchProduct(barcodeData.text);
     }).catch(err => {
         console.log('Error', err);
     });
  }

Add a function to input the product number (PLU) or barcode text manually.

  checkManually() {
    this.matchProduct(this.productnumber);
  }

Add a function to match the product number (PLU) or barcode text with the SQLite product table.

  matchProduct(productnumber: string) {
    this.sqlite.create({
      name: 'pricechecker.db',
      location: 'default'
    }).then((db: SQLiteObject) => {
      db.executeSql('SELECT * FROM product WHERE plu = ? OR barcode = ?', [productnumber, productnumber])
      .then(res => {
        if (res.rows.length > 0) {
          console.log(res.rows.item);
          console.log(res.rows.item(0));
          this.plu = res.rows.item(0).plu;
          this.barcode = res.rows.item(0).barcode;
          this.name = res.rows.item(0).prodname;
          this.description = res.rows.item(0).proddesc;
          this.price = res.rows.item(0).price;
        } else {
          console.log('product not found!');
        }
      })
      .catch(e => console.log(e));
    }).catch(e => console.log(e));
  }

Add a function to clear the variables.

  clearForm() {
    this.plu = '';
    this.barcode = '';
    this.name = '';
    this.description = '';
    this.price = null;
    this.productnumber = '';
  }

Next, open and edit "src/app/home/home.page.html" then replace all HTML tags with this.

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Price Checker
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-card *ngIf="name !== ''">
    <ion-card-header>
      <ion-card-title>{{price | currency}}</ion-card-title>
      <ion-card-subtitle>{{name}}</ion-card-subtitle>
    </ion-card-header>
    <ion-card-content>
      <h4>PLU: {{plu}}</h4>
      <h4>Descrition: {{description}}</h4>
      <p>
        <ion-button (click)="clearForm()">
          <ion-icon slot="start" name="refresh"></ion-icon>
          Clear
        </ion-button>
        <ion-button (click)="scanBarcode()">
          <ion-icon slot="start" name="camera"></ion-icon>
          Scan
        </ion-button>
      </p>
    </ion-card-content>
  </ion-card>
  <ion-card *ngIf="name === ''">
    <ion-card-content>
      <p>
        <ion-button (click)="scanBarcode()">
          <ion-icon slot="start" name="camera"></ion-icon>
          Check
        </ion-button>
      </p>
    </ion-card-content>
  </ion-card>
  <ion-card>
    <ion-card-content>
      <ion-item>
        <ion-label position="floating">Manually Input</ion-label>
        <ion-input type="number" [(ngModel)]="productnumber"></ion-input>
      </ion-item>  
      <ion-button (click)="checkManually()">
        <ion-icon slot="start" name="send"></ion-icon>
        Scan
      </ion-button>
    </ion-card-content>
  </ion-card>
</ion-content>

Step #4: Run and Test the Ionic 5 Price Checker App on Device

Now, it's a time to run this Ionic 5 and SQLite offline Price checker app to the Android or iOS device. Type this command to add the Capacitor Android and iOS platforms.

npx cap add android
npx cap add ios

Next, build the Ionic 5 app by type this command.

npm run build

Copy the built Ionic 5 app to Android and iOS.

npx cap copy ios
npx cap copy android

To run this Ionic 5 app to the Android device run the Android studio by type this command.

npx cap open android

Then connect your device using the data cable or Android simulator then run this app from Android studio. To run this app to the iOS using XCode type this command.

npx cap open ios

Then connect your iPhone or iPad using a data cable or simulator then run this app from the XCode. If you are using an iPhone device, make sure you have to change the bundle ID to your domain that registered in the Apple Developer account.

And here the app looks like in the device.

Ionic 5 Tutorial: Create Offline Price Checker (Angular 9) Ionic 5 Tutorial: Create Offline Price Checker (Angular 9)

That it's, the Ionic 5 Tutorial: Create Offline Price Checker (Angular 9) using SQLite and BarcodeScanner plugins. You can get the full source code from 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!


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

.NET设计规范

.NET设计规范

克瓦林纳 / 葛子昴 / 人民邮电出版社 / 2006-7 / 49.00元

本书为框架设计师和广大开发人员设计高质量的软件提供了权威的指南。书中介绍了在设计框架时的最佳实践,提供了自顶向下的规范,其中所描述的规范普遍适用于规模不同、可重用程度不同的框架和软件。这些规范历经.net框架三个版本的长期开发,凝聚了数千名开发人员的经验和智慧。微软的各开发组正在使用这些规范开发下一代影响世界的软件产品。. 本书适用于框架设计师以及相关的专业技术人员,也适用于高等院校相关专业......一起来看看 《.NET设计规范》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具