angular - 在 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
})
}
谁能帮我为什么它显示未定义,如何连接它
你的帮助会很棒
提前致谢!
解决方案
这与套接字无关。这是一个 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
})
推荐阅读
- python - 使用字典获取列表内列表中的所有项目
- function - 如何用 lambda 项中的 Church 数字定义函数?
- java - Fortify : 反映跨站脚本
- javascript - 查找 `tsconfig.json` 中提到的绝对路径时出现 TypeScript 编译器错误
- python-3.x - 为什么 Pandas 不使用总体的全长来计算方差
- javascript - 错误:请求失败,javaScript 中的状态码为 422
- sql - 在 BigQuery 中,如何检查两个 ARRAY 的 STRUCT 是否相等
- cplex - 如何计算 OPL 元组中匹配条件的项目数
- draw.io - Draw.io - 如何使用命令行将所有选项卡导出到图像
- javascript - 将用户输入存储在本地存储中的特定数组中