Quantcast
Channel: Xiao Ling – Dynamsoft Developers
Viewing all articles
Browse latest Browse all 239

How to Use Dynamsoft JavaScript Barcode SDK in Angular

$
0
0

Dynamsoft JavaScript barcode SDK is built based on WebAssembly. In this article, I will illustrate how to build a simple web barcode reader app by using Dynamsoft JavaScript barcode SDK and Angular.

Using JavaScript Barcode SDK in an Angular CLI Project

Create an Angular CLI project

Install Angular CLI:

npm install -g @angular/cli

Create a new project:

ng new barcode-reader

Build and run the app:

ng serve --open

Use Dynamsoft JavaScript barcode library

Open src/index.html to add <script> elements. Declare ‘dynamsoft’ as a global variable:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>BarcodeReader</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script id="script"></script>
  <script >var dynamsoft = self.dynamsoft || {};
  </script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

Add an HTMLImageElement (loading animation), an HTMLInputElement (file picker) and an HTMLDivElement (text display) to src/app/app.component.html:

<div style="text-align:left">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img src="assets/loading.gif" style="margin-top:10px" id="anim-loading">
  <div>
    <input id="uploadImage" type="file" accept="image/bmp,image/jpeg,image/png,image/gif" (input)="readBarcode()">
  </div>
  <div><b>Barcode result:</b> {{results}}</div>
</div>
<router-outlet></router-outlet>

In src/app/app.component.ts, add a constructor() to initialize ‘dynamsoft’ and dynamically load the Dynamsoft JavaScript barcode library:

export class AppComponent {
    title = 'Dynamsoft Barcode Reader';
    results = '';
    reader;

    constructor() {
        const env = this;
        dynamsoft.dbrEnv = dynamsoft.dbrEnv || {};
        dynamsoft.dbrEnv.resourcesPath = 'https://demo.dynamsoft.com/dbr_wasm/js';
        //https://www.dynamsoft.com/CustomerPortal/Portal/TrialLicense.aspx
        dynamsoft.dbrEnv.licenseKey =
            't0068NQAAADAG7KITlB55pjkzxD1rnTRhcZ/KCqVoXp6vWXmjRUbhvkCl58F+mqFnhIo1Oul/qB0moA8nA1erzTPYsb4FVLk=';
        dynamsoft.dbrEnv.bUseWorker = true;
        dynamsoft.dbrEnv.onAutoLoadWasmSuccess = function() {
            env.reader = new dynamsoft.BarcodeReader();
            document.getElementById('anim-loading').style.display = 'none';
        };
        dynamsoft.dbrEnv.onAutoLoadWasmError = function(ex) {
            alert(ex);
        };

        let bMobileSafari =
            /Safari/.test(navigator.userAgent) &&
            /iPhone/.test(navigator.userAgent) &&
            !/Chrome/.test(navigator.userAgent);

        let script = document.getElementById('script');
        if (!bMobileSafari) {
            script.src = 'https://demo.dynamsoft.com/dbr_wasm/js/dbr-6.3.0.2.min.js';
        } else {
            // bMobileSafari
            // js for mobile(safari especially): smaller, compile quicker, need less memory, but not that stable
            script.src = 'https://demo.dynamsoft.com/dbr_wasm/js/dbr-6.3.0.2.mobile.min.js';
        }
    }
 }

Create a function readBarcode() for binding the HTMLInputElement:

readBarcode(): void {
        const env = this;
        let image = document.getElementById('uploadImage').files[0];
        if (!image) {
            alert('Please add an image');
            return;
        }
        this.reader
            .decodeFileInMemory(image)
            .then(function(results) {
                var txts = [];
                for (var i = 0; i < results.length; ++i) {
                    txts.push(results[i].BarcodeText);
                }
                env.results = JSON.stringify(txts);
            })
            .catch((ex) => {
                alert(ex);
            });
    }

That’s it. I can now successfully run the app:

Angular WebAssembly barcode

Fix Angular CLI errors

Although the web barcode reader runs well, there are some errors displayed in the command line tool:

angular error

Seeing so many errors makes me uncomfortable, and thus I have to fix them.

‘dynamsoft’ is a global variable which is invisible in app.component.ts. We can declare it as follows:

import { Component } from '@angular/core';

declare var dynamsoft: any;

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ]
})

To fix the property error, we can cast the corresponding HTML Elements with specific types:

if (!bMobileSafari) {
            (<HTMLScriptElement >script).src = 'https://demo.dynamsoft.com/dbr_wasm/js/dbr-6.3.0.2.min.js';
        } else {
            // bMobileSafari
            // js for mobile(safari especially): smaller, compile quicker, need less memory, but not that stable
            (<HTMLScriptElement >script).src = 'https://demo.dynamsoft.com/dbr_wasm/js/dbr-6.3.0.2.mobile.min.js';
        }
let image = (<HTMLInputElement>document.getElementById('uploadImage')).files[0];

Source Code

https://github.com/dynamsoft-dbr/javascript-barcode/tree/master/examples/angular

The post How to Use Dynamsoft JavaScript Barcode SDK in Angular appeared first on Code Pool.


Viewing all articles
Browse latest Browse all 239

Latest Images

Trending Articles



Latest Images