1

Having trouble with the following Angular5 code:

constructor(protected snackBar: MatSnackBar) {}

openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000,
    });
}    

ngOnInit() {        
    const socket = io();
    socket.on('notification', function (data) {  
        this.openSnackBar(data.message,"Undo");
    });
}

Depending on when my endpoint invokes the websocket (using socket.io), which all works fine, I would like to use Angular Material snackbar to display my data.message from socket.

Unfortunately, I am receiving the following error:

ERROR TypeError: "this.openSnackBar is not a function"

Unsure what I am doing wrong here and is the above possible?

tonyf
  • 34,479
  • 49
  • 157
  • 246

1 Answers1

3

Use arrow function => instead -

socket.on('notification', (data) => {  
    this.openSnackBar(data.message,"Undo");
});

Because, it does not have its own this

robbannn
  • 5,001
  • 1
  • 32
  • 47
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215