在 Angular 4 的套接字中获取新消息时无法读取旧消息列表
Unable to read oldmessage list while getting new message in socket in Angular 4
我正在使用 socket.io 进行实时聊天,并且在发送任何新消息时我能够通过套接字获取消息,但是当我尝试与旧消息列表连接时,我的旧消息列表显示未定义。
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
})
}
任何人都可以帮助我为什么它显示未定义,如何连接它
你的帮助会很棒
提前致谢!
这与套接字无关。这是一个 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
})
我正在使用 socket.io 进行实时聊天,并且在发送任何新消息时我能够通过套接字获取消息,但是当我尝试与旧消息列表连接时,我的旧消息列表显示未定义。
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
})
}
任何人都可以帮助我为什么它显示未定义,如何连接它
你的帮助会很棒
提前致谢!
这与套接字无关。这是一个 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
})