0

I imported a custom confirm dialog into a function and "this" went undefined everywhere except for the dialog function.

This is the function:

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");
      }
    );
  }

For the confirmDialogService this is defined like so this: this and everywhere else it's any

Antoniusz
  • 35
  • 5

1 Answers1

4

Prefer to use arrow functions.

For example :

function(arg) {
   ...
}

become :

(arg) => {
   ...
}

An arrow function will inherit scope from caller method. So this will be the same.

Your code should look like 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")
  );
}

You can read about arrow functions :

Thierry Falvo
  • 5,892
  • 2
  • 21
  • 39