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

标签 angular typescript

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

相关文章:

angular - 使用 MAT DIALOG Angular 将数据传递给函数

typescript - 检查函数签名

javascript - angular2 在模板中显示计算数据

Angular 2 单元测试 - 获取错误无法加载 'ng:///DynamicTestModule/module.ngfactory.js'

javascript - 在使用该服务的所有组件中显示 Angular 服务中的更改

javascript - 一年后,仍然在单元测试、集成测试和端到端测试中挣扎

javascript - 使 Angular 2 组件下载并运行脚本

angular - Typescript 错误 - Angular AoT 构建失败 - Node.js + Ionic 移动应用程序

typescript - 为什么 ES2015 模块语法优于自定义 TypeScript 命名空间?

jquery - 使用 RESTful Webservice 完成 Monaco 编辑器代码