0

I have a strange error when trying to push some strings to an array.

This might be a duplicate but I have found no answer in 50 threads..

Cannot read property 'push' of undefined.

Here is what I am trying to do:

public messageList = [];

receive = function(msg) {
  if (msg.length > 0) {
    this.messageList.push(msg);
  }
}

receiveis a callback from socket.io.

.. where msg is a string.

I also tried public messageList: Array<string> = []; without success..

What can I do?

EDIT: as someone pointed it out, the method is a callback from socket.io

Martin
  • 55
  • 6

1 Answers1

0

declare this as self then use self in callback function

e.g

 let self = this;
 public messageList = [];

 receive = function(msg) {
   if (msg.length > 0) {
     self.messageList.push(msg);
  }
 }
Mr code.
  • 307
  • 1
  • 14