首页 > 解决方案 > 无法读取或设置作为参数传递的函数内部的属性

问题描述

deleteDialog(item, func: Function) {
    this.dialogService
      .open(ConfirmDialogComponent, {
        context: {
          title:"Are you sure?",
          cancelClss: "info",
          confirmClss: "danger",
        },
      })
      .onClose.subscribe((confirmed) => {
        if (confirmed) func(item);
      });
  }

这个函数所做的只是打开一个对话框并返回结果,如果动态确认,我想传递我想要执行的函数,以便能够在其他地方重用对话框。
例如我有这个功能

deleteCurrencyImplementation(cur: Currency) {
 this.showSpinner = true; 
 ...
 }

该函数被执行并且对象被正确传递,但是如果我尝试读取/设置内部的任何内容,例如显示微调器,这是一个public属性并设置为trueAngular TypeError,因为undefined.
这就是我在 html 中传递函数的方式。

 <show-datasource 
[tableConfig]="config" [data]="currenciesFromApi"
(deleteEmitter)="deleteDialog($event,deleteCurrencyImplementation)"> 
 </show-datasource>

我错过了什么?

标签: angulartypescript

解决方案


将您的回调函数绑定this到. 这可以通过多种方式完成。

像这样声明函数:

deleteCurrencyImplementation = (cur: Currency) => {
 this.showSpinner = true; 
 ...
 }

在调用它之前绑定:

    .onClose.subscribe((confirmed) => {
            if (confirmed) {
               const bounded = func.bind(this);
               bounded(item);
            }
          });

推荐阅读