Angular5 typescript when calling a function within ngOnInit

233 Views Asked by At

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?

1

There are 1 best solutions below

1
On BEST ANSWER

Use arrow function => instead -

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

Because, it does not have its own this