0

I want to call openSnackBar but I get exception. Anyone could please help me how to deal with outer method calling from nested functions?

export class DetailsComponent implements OnInit, OnDestroy
{
updateTodoPromise.then(function (fulfilled) {
            // yay, you got a new phone
            this.openSnackBar('Task saved successfully!', 'CLOSE');
        })
        .catch(function (error) {
            // ops, mom don't buy it
            console.log(error.message);
            this.openSnackBar('Task saved successfully!','CLOSE');
        });

    }

    public openSnackBar(full: string, full2: string) {
        this.snackBar.open(full, full2, {
            duration: 5000,
        });
    }
matio
  • 397
  • 2
  • 14

1 Answers1

2

Use ES6 double arrow notation to conserve the this scope.

export class DetailsComponent implements OnInit, OnDestroy
{
updateTodoPromise.then( fulfilled => { // <--- here
            // yay, you got a new phone
            this.openSnackBar('Task saved successfully!', 'CLOSE');
        })
        .catch( error => {  // <--- and here
            // ops, mom don't buy it
            console.log(error.message);
            this.openSnackBar('Task saved successfully!','CLOSE');
        });

    }

    public openSnackBar(full: string, full2: string) {
        this.snackBar.open(full, full2, {
            duration: 5000,
        });
    }
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63