Angular 插座发射次数过多,can';别关上它

Angular 插座发射次数过多,can';别关上它,angular,socket.io,Angular,Socket.io,我正在尝试使用socket.io在我的网站上的聊天模块中的用户之间发送消息 消息处理得很好,但行为很奇怪,它来自我将socket.io的jquery文档翻译成javascript的方式 第一次发送一次。 第二个很好。 第三次是两次。 第四次是三次。 等等 例如,如果我键入:foo、void、int、double,将显示: 福 空虚 空虚 int int int 双重的 双重的 双重的 双重的 以下是我目前的代码: html: <form action="" [formGroup]="mes

我正在尝试使用socket.io在我的网站上的聊天模块中的用户之间发送消息

消息处理得很好,但行为很奇怪,它来自我将socket.io的jquery文档翻译成javascript的方式

第一次发送一次。 第二个很好。 第三次是两次。 第四次是三次。 等等

例如,如果我键入:
foo、void、int、double,将显示:

空虚

空虚

int

int

int

双重的

双重的

双重的

双重的

以下是我目前的代码:

html

<form action="" [formGroup]="messageForm" (ngSubmit)="sendMessage()">
  <input id="message" formControlName="message" #message class="form-control" class="messageInput" autocomplete="off"/>
  <button type="submit" class="btn btn-primary btn-lg btn-block">SEND</button>
</form>
sendMessage() {
  if (this.messageForm.valid) {
    this.message = this.messageForm.get('message').value;
    this.messageForm.reset();
    this.socket.emit('chat message', this.message);
    this.socket.on('chat message', this.receive);
  }
}

receive = function(msg) {
  console.log('receive called'); // called incrementally over time, 1, 22, 333 etc..
  const li = document.createElement('li');
  document.getElementById('messageList').appendChild(li);
  li.innerHTML = msg;
};
后端

io.on('connection', function(socket){
    socket.on('disconnect', function(){
    });
   socket.on('chat message', function(msg){
        io.emit('chat message', msg);
   });
 });
以下是socket.io教程代码供参考

$(function () {
    var socket = io();
    $('form').submit(function(e){
        e.preventDefault(); // prevents page reloading
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
         return false;
    });
    socket.on('chat message', function(msg){
        $('#messages').append($('<li>').text(msg));
    });
});
$(函数(){
var socket=io();
$('form')。提交(函数(e){
e、 preventDefault();//防止页面重新加载
emit('chat message',$('#m').val());
$('m').val('');
返回false;
});
socket.on('chat message',函数(msg){
$(“#消息”).append($(“
  • ”).text(msg)); }); });
  • 在做了一些研究和“console.logging”之后,它看起来像是
    receive()
    被指数调用,第一条消息调用一次,第二条消息调用两次,等等。。我认为我缺少从socket.io jquery的代码到角度自适应的
    return false
    的正确翻译

    我能做什么?明白了

    this.socket.on('chat message',this.receive')不应位于
    sendMessage()
    函数内。它存在于要声明一次的套接字初始化中:

    try {
        this.socket = io.connect('http://localhost:3000');
        this.socket.on('chat message', this.receive);
      } catch (e) {
          console.log('Could not connect socket.io');
      }
    

    有人能帮忙吗?:)