【问题标题】:Socket IO using functions in event listener在事件监听器中使用函数的套接字 IO
【发布时间】:2017-05-03 07:12:35
【问题描述】:

我在 Angular 2 中使用套接字 io,但遇到以下问题:

this.socket.on('response_navbar', function (data) {
  console.log(data.entryTypeCollection);
  this.test123();
});

test123() {
   console.log('Test');
}

在事件'response_navbar' 到来之后,console.log() 正在工作,但是当我尝试调用函数this.test123(); 时,我收到错误

谁能帮帮我?

【问题讨论】:

    标签: angular typescript web socket.io


    【解决方案1】:

    由于您使用的是this,因此您应该使用箭头函数来保留上下文。

    this.socket.on('response_navbar', (data) => {
      console.log(data.entryTypeCollection);
      this.test123();
    });
    

    【讨论】:

    • 非常感谢。但是你能回答,为什么 function(){} 和 () => {} 有意义???
    • @BakhtierGaibulloev 这是ES6的新特性,没有箭头功能,我们也可以手动绑定this。
    • this 关键字自动被匿名的function () {} 绑定到this.socket。通过使用箭头函数() => {} 或手动绑定function () {}.bind(this),该函数继承了您所期望的周围上下文。
    【解决方案2】:

    我有这段代码用 SocketIO 初始化我的 NodeJs 服务器

     var io = require('socket.io').listen(server)
        io.on('connection', function (socket) {
        ....
        }
    

    这不是必须的,因为this.test123 引用了socket.on 中的上下文

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 1970-01-01
      • 2022-01-25
      • 2014-12-03
      • 1970-01-01
      相关资源
      最近更新 更多