【发布时间】: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