【问题标题】:Cannot read property 'emit' of undefined "Socket + Angular + Node "无法读取未定义“Socket + Angular + Node”的属性“发射”
【发布时间】:2019-01-01 01:18:23
【问题描述】:

我在我的节点服务器中创建了这个事件:

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');
}

在我的聊天组件.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:每当我点击发送消息时,套接字总是断开并重新连接

【问题讨论】:

    标签: node.js angular sockets mean


    【解决方案1】:

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

    【讨论】:

    • 我已经取消了它:export class ChatComponent implements OnInit { sender : any ;接收器:任何;参考:任何;令牌:任何;消息:任何;插座;
    • 我认为在构造函数中你需要这样:this.socket = io('localhost:4000') 然后你可以在 onSendMessage 函数中使用它
    • 是的,它有效。我有一个问题,当我发送消息时,套接字断开连接然后重新连接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    相关资源
    最近更新 更多