【问题标题】:Angular7 "this" is undefined [duplicate]Angular7“this”未定义[重复]
【发布时间】:2019-11-11 16:21:24
【问题描述】:

我将一个自定义确认对话框导入到一个函数中,但除了对话框函数之外,“this”在所有地方都未定义。

这是函数:

onDelete(CTId) {
    this.confirmDialogService.confirmThis( 
      "Confirm Delete",
      function() {
          this.service.deleteContactDetail(CTId).subscribe(
          res => {
            this.service.refreshList();
            this.toastr.warning("Deleted Successfully", "Contact Details");
          },
          err => {
            console.log(err);
            this.toastr.error("Failed to Delete");
          }
        );
      },
      function() {
        console.log("closed dialog");
      }
    );
  }

对于confirmDialogService,它是这样定义的this: this,而在其他任何地方它都是any

【问题讨论】:

  • function() { 更改为 () => { 并阅读一些有关箭头函数的信息(尽管我对 this: this 感到困惑)。
  • 箭头不起作用,表示预期 {
  • 抱歉,我把它改成了function() => {,而不是() => {。真的需要阅读。

标签: angular typescript


【解决方案1】:

更喜欢使用箭头函数。

例如:

function(arg) {
   ...
}

成为:

(arg) => {
   ...
}

箭头函数将从调用者方法继承范围。所以this 会是一样的。

您的代码应如下所示:

onDelete(CTId) {
  this.confirmDialogService.confirmThis( 
    "Confirm Delete",
    () => {
      this.service.deleteContactDetail(CTId).subscribe(
        res => {
          this.service.refreshList();
          this.toastr.warning("Deleted Successfully", "Contact Details");
        },
        err => {
          console.log(err);
          this.toastr.error("Failed to Delete");
        }
      );
    },
    () => console.log("closed dialog")
  );
}

你可以阅读arrow functions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 2017-11-26
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    相关资源
    最近更新 更多