Creating an Angular application to read barcodes.
barcode-scanner.component.html
<form #f="ngForm" class="mt-3 text-center" id="myform" (ngSubmit)="onSubmit(f)">
<div class="text-center">
<input type="text" maxlength="13" name="barcode" class="form-control text-center mt-2" [(ngModel)]="barcode" placeholder="Barcode">
</div>
</form>
barcode-scanner.component.ts
export class BarcodeScannerComponent implements OnInit {
barcode:string;
codEspec:Number;
DiaHoraEspecs:string;
scans: Ticket[];
constructor(private ticketlineservice: TicketlineService,
private activatedRoute: ActivatedRoute, private snackBar: MatSnackBar) {
this.activatedRoute.queryParams.subscribe(params => {
this.codEspec = params['CodEspec'];
this.DiaHoraEspecs = params['DiaHoraEspecs'];
});
}
ngOnInit() {
}
onSubmit(f: NgForm){
var element = document.getElementById("ticket");
var scannedCodes = []; //array to store scanned barcodes
scannedCodes.push(this.barcode); //insert scanned barcode inside array
for(var i = 0; i < scannedCodes.length; i++){
if(scannedCodes[i] == this.barcode){ //compare scanned barcode with the ones inside the array
this.snackBar.open("Ticket already scanned!",'', {
duration: 2000,
verticalPosition: 'top',
horizontalPosition: 'end',
panelClass: ['snack-error'],
});
element.setAttribute("style", "visibility: hidden;");
f.resetForm();
}else{
this.ticketlineservice.CheckTicket(this.barcode, this.codEspec, this.DiaHoraEspecs).subscribe(scans => {
if(Array.isArray(scans)){
this.scans = scans;
}
else if(typeof scans === 'string' ){
this.scans = [];
}
else{
this.scans = [scans];
}
// console.log('scans = ' + scans);
if(scans != null){
this.snackBar.open("Ticket is valid!",'', {
duration: 2000,
verticalPosition: 'top',
horizontalPosition: 'end',
panelClass: ['snack-success'],
});
element.setAttribute("style", "visibility: visible;");
}else{
this.snackBar.open("Ticket not found!",'', {
duration: 2000,
verticalPosition: 'top',
horizontalPosition: 'end',
panelClass: ['snack-error'],
});
element.setAttribute("style", "visibility: hidden;");
}
f.resetForm();
});
}
}
}
refresh(): void {
window.location.reload();
}
}
Issue: I am facing a problem with my Angular application that consumes an API for checking barcode validity. The API does not provide a status indicating whether a barcode has been previously scanned or not. To address this, I have created an array to store all scanned barcodes and compare new scans with the values in the array. However, each time a new barcode is scanned, it triggers the first condition even when the barcode is not in the array. Additionally, I would appreciate any suggestions on how to persist these values so they are not lost when the user reloads the page.