I am looking to integrate the BarcodeDetector into my Angular application. After testing the API, I used the following code:
HTML:
<!DOCTYPE html>
<html lang="en>
<head>
<script src="./script.js"></script>
</head>
<body>
<button onclick="scan()">Click here</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 += 'Initiating scan\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';
}
}
The implementation worked flawlessly. I encountered a NotSupported
error on PC but successfully decoded the barcode on my mobile device.
As TypeScript is an extension of JavaScript, I assumed porting the code would be straightforward. However, it proved to be more complex than anticipated. The HTML setup in the Angular app remained similar. Below is the component code:
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;
}
}
}
The check for detector existence yields true, indicating that the detector is available. However, I encounter the following error on both PC and mobile:
TypeError: (void 0) is not a constructor
This issue seems related to the declaration of the decoder, and I'm unsure how to proceed with resolving it.