【问题标题】:Implementing a barcode scanner in Angular 4在 Angular 4 中实现条码扫描器
【发布时间】:2020-11-05 04:19:19
【问题描述】:

我正在尝试使用 Angular 4 实现条形码扫描仪,使用这个插件 - https://github.com/isonet/angular-barcode-scanner

在我的scanner.component.ts 页面我有;

    import { Component, OnInit} from '@angular/core';
    import 'angular-barcode-scanner';
...

在我的app.module.ts 文件中;

  ....
import { BarcodeScanner} from 'angular-barcode-scanner';

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        RouterModule.forRoot(routes),
        LoginModule,
        SignupModule,
        DashboardModule,
        ReactiveFormsModule,
        BarcodeScanner
      ],
      providers: [
        DataService,
        TokenService
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

然后在我的scanner.component.html 文件中;

<barcode-scanner separator-char="separatorChar" trigger-char="triggerChar" scan-callback="scanCallback"
                trigger-callback="triggerCallback"></barcode-scanner>
        </div>
    </div>

但是,我在控制台中收到以下错误

Uncaught ReferenceError: angular is not defined
    at Object.defineProperty.value (angular-barcode-scanner.js:1)
    at r (angular-barcode-scanner.js:1)
    at Object.defineProperty.value (angular-barcode-scanner.js:1)
    at angular-barcode-scanner.js:1
    at t (angular-barcode-scanner.js:1)
    at Object.<anonymous> (angular-barcode-scanner.js:1)
    at __webpack_require__ (bootstrap 0689b0e…:52)
    at Object.152 (bsElement.routes.ts:9)
    at __webpack_require__ (bootstrap 0689b0e…:52)
    at Object.413 (chart.module.ts:12)
    at __webpack_require__ (bootstrap 0689b0e…:52)
    at Object.153 (chart.component.ts:11)
    at __webpack_require__ (bootstrap 0689b0e…:52)
    at Object.155 (dashboard.component.ts:12)
    at __webpack_require__ (bootstrap 0689b0e…:52)
Object.defineProperty.value @ angular-barcode-scanner.js:1
r @ angular-barcode-scanner.js:1
Object.defineProperty.value @ angular-barcode-scanner.js:1
(anonymous) @ angular-barcode-scanner.js:1
t @ angular-barcode-scanner.js:1
(anonymous) @ angular-barcode-scanner.js:1
__webpack_require__ @ bootstrap 0689b0e…:52
152 @ bsElement.routes.ts:9
__webpack_require__ @ bootstrap 0689b0e…:52
413 @ chart.module.ts:12
__webpack_require__ @ bootstrap 0689b0e…:52
153 @ chart.component.ts:11
__webpack_require__ @ bootstrap 0689b0e…:52
155 @ dashboard.component.ts:12
__webpack_require__ @ bootstrap 0689b0e…:52
405 @ app.module.ts:40
__webpack_require__ @ bootstrap 0689b0e…:52
404 @ main.ts:12
__webpack_require__ @ bootstrap 0689b0e…:52
424 @ table.module.ts:12
__webpack_require__ @ bootstrap 0689b0e…:52
393 @ src async:7
__webpack_require__ @ bootstrap 0689b0e…:52
733 @ main.bundle.js:2545
__webpack_require__ @ bootstrap 0689b0e…:52
webpackJsonpCallback @ bootstrap 0689b0e…:23
(anonymous) @ main.bundle.js:1
bundle.js:19 Uncaught ReferenceError: ng is not defined
    at N (bundle.js:19)
    at VueComponent.ready (bundle.js:15)
    at VueComponent.LN.M._callHook (bundle.js:5)
    at VueComponent.z (bundle.js:5)
    at VueComponent.N (bundle.js:5)
    at VueComponent.M.$emit (bundle.js:5)
    at VueComponent.LN.M._callHook (bundle.js:5)
    at z (bundle.js:5)
    at VueComponent.M.$before (bundle.js:5)
    at CN.transition (bundle.js:6)
    at CN.mountComponent (bundle.js:6)
    at bundle.js:6
    at bundle.js:6
    at N (bundle.js:4)
    at ON.QN.M._resolveComponent (bundle.js:5)
N @ bundle.js:19
ready @ bundle.js:15
LN.M._callHook @ bundle.js:5
z @ bundle.js:5
N @ bundle.js:5
M.$emit @ bundle.js:5
LN.M._callHook @ bundle.js:5
z @ bundle.js:5
M.$before @ bundle.js:5
transition @ bundle.js:6
mountComponent @ bundle.js:6
(anonymous) @ bundle.js:6
(anonymous) @ bundle.js:6
N @ bundle.js:4
QN.M._resolveComponent @ bundle.js:5
resolveComponent @ bundle.js:6
setComponent @ bundle.js:6
bind @ bundle.js:6
CN._bind @ bundle.js:6
Gz @ bundle.js:4
(anonymous) @ bundle.js:4
M._compile @ bundle.js:5
M.$mount @ bundle.js:5
M._init @ bundle.js:4
Y.M._init @ bundle.js:19
ON @ bundle.js:5
(anonymous) @ bundle.js:3
zone.js:155 Uncaught TypeError: Cannot read property 'geAdapter' of undefined
    at WebSocket._ws.onopen (eval at M.exports (bundle.js:3), <anonymous>:97:46)
    at WebSocket.wrapFn [as _onopen] (zone.js:851)
    at ZoneDelegate.invokeTask (zone.js:262)
    at Zone.runTask (zone.js:151)
    at WebSocket.ZoneTask.invoke (zone.js:332)
_ws.onopen @ VM53541:97
wrapFn @ zone.js:851
ZoneDelegate.invokeTask @ zone.js:262
Zone.runTask @ zone.js:151
ZoneTask.invoke @ zone.js:332

感谢任何帮助。

【问题讨论】:

    标签: angular typescript barcode-scanner


    【解决方案1】:

    QuaggaJS 是一个完全用 JavaScript 编写的条码扫描器,支持实时定位和解码各种类型的条码,例如EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93 and CODABAR。该库还能够使用 getUserMedia 直接访问用户的相机流。尽管代码依赖于繁重的图像处理,但即使是最近的智能手机也能够实时定位和解码条形码。

    使用 QuaggaJS,Angular example 进行条码扫描

    用于角度条码扫描器的 NPM Angular 模块:

    import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
    import Quagga from 'quagga';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      barcode = '';
      barcodeResult;
      configQuagga = {
        inputStream: {
          name: 'Live',
          type: 'LiveStream',
          target: '#inputBarcode',
          constraints: {
            width: { min: 640 },
            height: { min: 480 },
            aspectRatio: { min: 1, max: 100 },
            facingMode: 'environment', // or user
          },
          singleChannel: false // true: only the red color-channel is read
        },
        locator: {
          patchSize: 'medium',
          halfSample: true
        },
        locate: true,
        numOfWorkers: 4,
        decoder: {
          readers: ['code_128_reader']
        }
      };
      constructor(private ref: ChangeDetectorRef) { }
    
      ngOnInit() {
        console.log('Barcode: initialization');
      }
    
      testChangeValues() {
        this.barcode = 'Code-barres bidon : 0123456789';
      }
    
      startScanner() {
        this.barcode = '';
        this.ref.detectChanges();
    
        Quagga.onProcessed((result) => this.onProcessed(result));
    
        Quagga.onDetected((result) => this.logCode(result));
    
        Quagga.init(this.configQuagga, (err) => {
          if (err) {
            return console.log(err);
          }
          Quagga.start();
          console.log('Barcode: initialization finished. Ready to start');
        });
    
    
      }
    
      private onProcessed(result: any) {
        const drawingCtx = Quagga.canvas.ctx.overlay;
        const drawingCanvas = Quagga.canvas.dom.overlay;
    
        if (result) {
          if (result.boxes) {
            drawingCtx.clearRect(0, 0, parseInt(drawingCanvas.getAttribute('width'), 10), parseInt(drawingCanvas.getAttribute('height'), 10));
            result.boxes.filter(function (box) {
              return box !== result.box;
            }).forEach(function (box) {
              Quagga.ImageDebug.drawPath(box, { x: 0, y: 1 }, drawingCtx, { color: 'green', lineWidth: 2 });
            });
          }
    
          if (result.box) {
            Quagga.ImageDebug.drawPath(result.box, { x: 0, y: 1 }, drawingCtx, { color: '#00F', lineWidth: 2 });
          }
    
          if (result.codeResult && result.codeResult.code) {
            Quagga.ImageDebug.drawPath(result.line, { x: 'x', y: 'y' }, drawingCtx, { color: 'red', lineWidth: 3 });
          }
        }
      }
    
      private logCode(result) {
        const code = result.codeResult.code;
       
        if (this.barcode !== code) {
          this.barcode = 'Code-barres EAN : ' + code;
          this.barcodeResult=result.codeResult;
          this.ref.detectChanges();
          console.log(this.barcode);
          console.log(this.barcodeResult);
    
          // this.barcodeValue = result.codeResult.code;
          // this.barcodeResult=result.codeResult
          // console.log("this.barcodeValue",this.barcodeValue)
    
          console.log("JSON.stringify(result.codeResult)",JSON.stringify(result.codeResult))
          console.log("Result",result)
          console.log("JSON.stringify(result)",JSON.stringify(result))
          // console.log("this.barcodeResult",this.barcodeResult.json())
          Quagga.stop();
        }
    
      }
    
    }
    #interactive.viewport {
        position: relative;
        width: 100%;
        height: auto;
        overflow: hidden;
        text-align: center;
    }
    
    #interactive.viewport>canvas,
    #interactive.viewport>video {
        max-width: 100%;
        width: 100%;
    }
    
    canvas.drawing,
    canvas.drawingBuffer {
        position: absolute;
        left: 0;
        top: 0;
    }
    h1 {
        color: white;
        background-color: #ff6600;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
        /* TODO style temporaire en attendant de migrer dans un autre composant */
        margin: auto !important;
        padding: 0px !important;
        height: 40px;
        line-height: 40px;
    }
    <div>
      <ngb-alert type="info" [dismissible]="false">
          <strong>Je scanne</strong> le code-barres pour voir les ODR.
      </ngb-alert>
    </div>
    <div *ngIf="barcode">
      <ngb-alert type="success" [dismissible]="false">
          {{ barcode }}
      </ngb-alert>
    </div>
    
    <button type="button" class="btn btn-warning" (click)="startScanner()">
      Démarrer le scan du code-barres
    </button>
    
    <div class="input-group">
     
      <div id="inputBarcode" style="position: static">
          <div id="interactive" class="viewport"></div>
      </div>
    </div>

    GitHub Reference Link

    【讨论】:

    【解决方案2】:

    https://github.com/isonet/angular-barcode-scanner 是一个 AngularJS(V1) 应用程序,您似乎正在构建 Angular(V4 可能是?) 应用程序。我不认为你可以 就这样使用&lt;barcode-scanner&gt;

    【讨论】:

    • 是的 Angular V4... 我正在努力寻找任何 V2 / V4 版本
    • 看起来是用来生成条形码的,我想用相机(iOS / Android)/网络摄像头读取它们
    • 对不起,我的错。在建议之前应该阅读描述。如果您使用的是 NativeScript,developer.telerik.com/featured/… 可能会有所帮助。如果没有,那么您可能可以参考这个并制作自己的 Angular2 组件,并且可以将它开源:) 作为 Angular2 模块。
    【解决方案3】:

    Chrome 已在其版本 83 中发布了 Shape Detection API,其中包括 Barcode Detector API。因此,如果您只关注 Chrome 用户,比如我的情况,我建议您使用 ng-barcode-detector 包。

    【讨论】:

    • 我收到错误,“未捕获的 DOMException:条码检测服务不可用。”在触发检测()时。看起来 chrome 在 chrome 84 上不支持此 API。如果这仅适用于移动设备,谁能提供帮助?
    【解决方案4】:

    Angular 10你可以使用这个模块ngx-barcode-scanner

    文档: https://github.com/julienboulay/ngx-barcode-scanner

    import { Component, ViewChild, AfterViewInit } from "@angular/core";
    import { BarecodeScannerLivestreamComponent } from "ngx-barcode-scanner";
    
    @Component({
      selector: "demo-app",
      template: `
        <barcode-scanner-livestream
          type="code_128"
          (valueChanges)="onValueChanges($event)"
          (started)="(onStarted)"
        ></barcode-scanner-livestream>
        <div [hidden]="!barcodeValue">
          {{ barcodeValue }}
        </div>
      `,
    })
    export class Demo implements AfterViewInit {
      @ViewChild(BarecodeScannerLivestreamComponent)
      barecodeScanner: BarecodeScannerLivestreamComponent;
    
      barcodeValue;
    
      ngAfterViewInit() {
        this.barecodeScanner.start();
      }
    
      onValueChanges(result) {
        this.barcodeValue = result.codeResult.code;
      }
    
      onStarted(started) {
        console.log(started);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多