Skeptical Ant
Skeptical Ant

Reputation: 384

Cannot read or set properties inside function that is being passed as a parameter

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

All this function does is that it opens a dialog and returns the result, I want to pass the function that I want to execute if confirmed dynamically to be able to reuse the dialog elsewhere.
For example I have this function

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

the function gets executed and the object is being passed correctly but if I try to read / set anything inside for example show spinner, which is a public property and set to true Angular throws TypeError because of undefined.
This is how I pass the function inside html.

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

What am I missing?

Upvotes: 0

Views: 54

Answers (1)

lbsn
lbsn

Reputation: 2412

Bind you callback function to this. This can be done in multiple ways.

Declare the function like this:

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

Bind before calling it:

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

Upvotes: 2

Related Questions