在 Angular 4 的套接字中获取新消息时无法读取旧消息列表



我正在使用 socket.io 进行实时聊天,当发送任何新消息时,我能够通过套接字获取消息,但是当我尝试与旧消息列表连接时,我的旧消息列表显示未定义。

在消息成功发送回数据库
后立即触发,我正在使用套接字

ngOnInit() {
this.socket.emit('init');
this.socket.on('message',function(data){
console.log(data) // here new message is receiving when sent new message
this.oldMessageList = this.oldMessageList.conact(data)// but oldmessage list showing undefined
})

}

谁能帮我为什么它显示未定义,如何连接它

您的帮助会很棒

提前感谢!

这与套接字无关。这是一个JavaScript提示。
您必须使用箭头功能。如果没有,this不是指您的想法。

this.socket.on('message',data => { // arrow function here
console.log(data) // here new message is receiving when sent new message
this.oldMessageList = this.oldMessageList.conact(data)// this will refer to youtr class, so this.oldMessageList will be defined
})

或使用老式提示:

var that = this
this.socket.on('message',function(data) { // old school function using "that"
console.log(data) // here new message is receiving when sent new message
that.oldMessageList = that.oldMessageList.conact(data)// "that" is defined
})

最新更新