首页 > 解决方案 > 在 Angular 4 的套接字中获取新消息时无法读取旧消息列表

问题描述

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


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

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
})

}

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

你的帮助会很棒

提前致谢!

标签: angularsocket.ioconcat

解决方案


这与套接字无关。这是一个 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
})

推荐阅读