我在节点服务器中创建了此事件:

socket.on('hello' , function (data) {console.log('hello from the other side');})


在我的聊天组件上:

constructor(private authService:AuthService,private router : Router) {
const socket=io('http://localhost:4000');
console.log(socket);}


onSendMessage(){
console.log('yep yep');
console.log(this.socket);
this.socket.emit('hello');
}


在我的聊天component.html上:

<div class="col-md-8">
            <div class="chat" id="chat">        </div>
            <form (ngSubmit)="onSendMessage()">
                  <div class="form-group">
                        <label>Enter Message</label>
                        <textarea class="form control" id="message"></textarea>
                        <br/>
                        <input type="submit" class="btn btn-primary" value="Send Message"/>
                  </div>
            </form>
      </div>


结果是这样的:


  无法读取未定义的属性“发出”
      在ChatComponent.push ../ src / app / components / chat / chat.component.ts.ChatComponent.onSendMessage中


这是Web控制台的图像:

PS:每当我单击“发送消息”时,套接字始终断开并重新连接

最佳答案

我认为问题在于套接字不是您的char组件的成员,应首先将其声明为用户this.socket的组件的成员,或者如果它是服务,则直接将其注入到构造函数中,然后成为成员您可以使用(this.socket)

07-27 18:49