我将一个外部 js 文件加载到我的 Angular 项目中,其中一个函数是我分配给我的一个函数的回调函数 fnBarcodeScanned(scan)
.
一切正常,因为我收到正确扫描条形码的警报,但下一行没有将条形码分配给我的局部变量 this.scanData
.
export class HomeComponent implements OnInit {
scanData: string;
ngOnInit() {
}
fnScanEnable() {
EB.Barcode.enable({ allDecoders: true }, this.fnBarcodeScanned);
this.scanData = "enabled: press HW trigger to capture.";
}
fnBarcodeScanned(scan) {
alert(scan.data);
this.scanData = "barcode: " + scan.data;
}
fnScanDisable() {
EB.Barcode.disable();
this.scanData = "disabled: press 'enable' to scan.";
}
}
如何绑定(bind)
fnBarcodeScanned(scan)
功能?在我看来,它在传递给回调时失去了与组件的绑定(bind)。
最佳答案
您可以使用 bind()
或 arrow function
使用 bind()
:
fnScanEnable() {
EB.Barcode.enable({ allDecoders: true }, this.fnBarcodeScanned.bind(this));
this.scanData = "enabled: press HW trigger to capture.";
}
使用
arrow function
:fnBarcodeScanned = (scan) => {
alert(scan.data);
this.scanData = "barcode: " + scan.data;
}
关于angular - Angular 中的绑定(bind)回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55615840/