【问题标题】:Chrome ShapeDetetion API BarcodeDetector works with javascript but not with typescriptChrome ShapeDetetion API BarcodeDetector 适用于 javascript 但不适用于 typescript
【发布时间】:2020-06-09 15:17:57
【问题描述】:

我想在 Angular 应用程序中实现 BarcodeDetector。我使用以下代码测试了 API:

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="./script.js"></script>
  </head>  
  <body>
    <button onclick="scan()">Click me</button>
    <img src="./barcode.gif">
    <pre></pre>
  </body>
</html>

JavaScript:

function scan() {
  const images = document.querySelectorAll('img');
  const pres = document.querySelectorAll('pre'); 
  try {
    pres[0].textContent += 'started\n';
      let barcodeDetector = new BarcodeDetector();
      pres[0].textContent += 'created and detecting\n';
      barcodeDetector.detect(images[0]).then(detectedCodes => {
      for (const barcode of detectedCodes) {      
        pres[0].textContent += barcode.rawValue  + '\n';
      }}).catch((e) => {
    pres[0].textContent += e + '\n';
  });
  } catch (e) {
    pres[0].textContent += e + '\n';
  }
}

而且效果很好。在 PC 上,我在手机上打开页面时收到了 NotSupported 错误和解码的条形码。

由于 TypeScript 是 JavaScript 的超集,我认为移植代码应该非常简单,但显然并非如此。 Angular 应用程序中的 HTML 几乎相同。组件代码如下:

var BarcodeDetector: any;

@Component({
    templateUrl: './index.component.html'
})
export class IndexComponent {

    @ViewChild('imgRef')
    image: ElementRef;

    hasBarcodeDetector = '';
    errors = '';
    scanData = '';

    constructor() {
        try {
            this.hasBarcodeDetector = 'BarcodeDetector' in window ? 'true' : 'false';
            const barcodeDetector = new BarcodeDetector();
            barcodeDetector.detect(this.image.nativeElement).then(detectedCodes => {
                for (const barcode of detectedCodes) {
                    this.scanData += barcode.rawValue + '\n';
                }
            });
        } catch (e) {
            this.errors = e;
        }
    }
}

检查检测器是否存在有效,因为我得到true,但在PC和移动设备上我都收到以下错误:

TypeError: (void 0) is not a constructor

我猜这与解码器的声明有关,但我真的不知道该怎么做。

【问题讨论】:

    标签: javascript angular typescript barcode


    【解决方案1】:

    我认为您的变量会意外覆盖window.BarcodeDetector。另请注意,您没有使用特征检测的结果。顺便说一句,特征检测现在应该以不同的方式进行,如最近更新的article 中所述:

    await BarcodeDetector.getSupportedFormats();
    /* On a macOS computer logs
      [
        "aztec",
        "code_128",
        "code_39",
        "code_93",
        "data_matrix",
        "ean_13",
        "ean_8",
        "itf",
        "pdf417",
        "qr_code",
        "upc_e"
      ]
    */
    

    这允许您检测您需要的特定功能,例如二维码扫描:

    if (('BarcodeDetector' in window) &&
        ((await BarcodeDetector.getSupportedFormats()).includes('qr_code'))) {
      console.log('QR code scanning is supported.');
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      相关资源
      最近更新 更多