gpt4 book ai didi

angular - Angular 中的绑定(bind)回调函数

转载 作者:行者123 更新时间:2023-12-04 15:46:20 26 4
gpt4 key购买 nike

我将一个外部 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com