Angular2:View未从Socket.io事件更新

时间:2022-05-15 11:41:34

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

顺便说一下,我的socket事件在index.html中正常工作

Any kind of help is appreciated.

任何形式的帮助表示赞赏。

1 个解决方案

#1


6  

Don't use function () because this way this doesn't point to the current class instance anymore. Use arrow functions instead:

不要使用function(),因为这样就不再指向当前的类实例了。请改用箭头功能:

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

#1


6  

Don't use function () because this way this doesn't point to the current class instance anymore. Use arrow functions instead:

不要使用function(),因为这样就不再指向当前的类实例了。请改用箭头功能:

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