我正在研究聊天应用程序,并在下面提到了问题。 问题:
节点js代码:
socket.on("sendMessage", (data) => {
console.log(data.msg + "..." + data.to);
socket.username = data.by;
io.to(data.to).emit("msgReceived", { "msg": data.msg, "by": socket.username }); //response back to client
});
socket.on("joinRoom", (data) => {
socket.join(data.sid);
console.log('You have joined in ' + data.sid + ' room');
......
客户端代码:
/* Passing value to the server */
isMessageSent() {
this.socket.emit('sendMessage', { "msg": this.umsg, "to": '123', "by": this.lgid, "lguser": this.lgid });
this.socket.on("msgReceived", function (data) {
console.log(data);
});
/* Response from the serve */
this.socket.on("msgReceived", function (data) {
console.log(data.by + "...." + this.lguser);
if (data.by == this.lguser) {
$("#chul").append("<li class='clr'> <p _ngcontent-c1 class='fu fl'>" + data.msg + "</p></li>");
} else {
$("#chul").append("<li class='clr'> <p _ngcontent-c1 class='fd fr'>" + data.msg + "</p></li>");
}
.....
答案 0 :(得分:0)
尝试一下。您必须绑定上下文。在here中了解有关上下文绑定的更多信息。
我创建了一个单独的函数来处理事件。而且我正在使用bind
方法来绑定上下文。
this.handleMessageReceivedEvent.bind(this)
您的代码应如下所示。
this.socket.on("msgReceived", this.handleMessageReceivedEvent.bind(this));
private handleMessageReceivedEvent(): void {
console.log(data.by+"...."+this.lguser);
if(data.by==this.lguser){
$("#chul").append("<li class='clr'> <p _ngcontent-c1 class='fu fl'>"+data.msg+"</p></li>");
}else{
$("#chul").append("<li class='clr'> <p _ngcontent-c1 class='fd fr'>"+data.msg+"</p></li>");
}
}