应用在角度读取条形码中。
read.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>
read.component.ts
export class ReadComponent implements OnInit {
barcode:string;
codEspec:Number;
DiaHoraEspecs:string;
reads: 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 barcodes = []; //array to store barcodes
barcodes.push(this.barcode); //insert barcode inside array
for(var i = 0; i < barcodes.length; i++){
if(barcodes[i] == this.barcode){ //compare barcode read with the ones inside the array
this.snackBar.open("Ticket already read!",'', {
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(reads => {
if(Array.isArray(reads)){
this.reads = reads;
}
else if(typeof reads === 'string' ){
this.reads = [];
}
else{
this.reads = [reads];
}
// console.log('reads = ' + reads);
if(reads != null){
this.snackBar.open("Ticket valid!",'', {
duration: 2000,
verticalPosition: 'top',
horizontalPosition: 'end',
panelClass: ['snack-sucess'],
});
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();
}
}
问题:因此,我有一个使用API的Angular应用程序,此api检查条形码是否有效。由于它没有某种状态,请说是否已被读取,所以我想在前端实现它。
因此,我创建了一个数组来存储每个读取的条形码,并将该数组中的值与读取的值进行比较。但是,每次读取新条形码时,即使条形码不在阵列内,它也会进入我的第一个if
状态。另外,如果可以给我一个存储值的想法,并且在用户重新加载页面时不丢失它们,我将不胜感激。