简体   繁体   English

Angular2:视图未从Socket.io事件更新

[英]Angular2: View is not updating from Socket.io event

I was simply trying to update my view when I receive an socket event. 当我收到套接字事件时,我只是试图更新我的视图。 My code in the component is something like below: 我在组件中的代码如下所示:

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

when I run this browser console show some errors: 当我运行此浏览器控制台时,显示一些错误:

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

btw, my socket event are working properly in index.html 顺便说一句,我的套接字事件在index.html中正常工作

Any kind of help is appreciated. 任何帮助都将受到赞赏。

Don't use function () because this way this doesn't point to the current class instance anymore. 不要使用function () ,因为这样一来this不指向当前的类实例了。 Use arrow functions instead: 改用箭头功能:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM