【问题标题】:Angular2: View is not updating from Socket.io eventAngular2:视图未从 Socket.io 事件更新
【发布时间】:2016-11-05 14:37:35
【问题描述】:

我只是在收到套接字事件时尝试更新我的视图。 我在组件中的代码如下所示:

constructor(private _zone: NgZone){
    this.socket = io.connect('http://localhost:3000');
    this.socket.on('someEvent', function(data) {
        this._zone.run(() => {
            this.dataItem = data.item;
            console.log(this.dataItem);
        });
    });
}

当我运行这个浏览器控制台时显示一些错误:

EXCEPTION: TypeError: Cannot read property 'run' of undefined

顺便说一句,我的套接字事件在 index.html 中正常工作

感谢任何形式的帮助。

【问题讨论】:

    标签: angularjs angular typescript websocket socket.io


    【解决方案1】:

    不要使用function (),因为这样this 不再指向当前类实例。改用箭头函数:

    this.socket.on('someEvent', (data) => {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多