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
Any kind of help is appreciated.
Don't use function ()
because this way this
doesn't point to the current class instance anymore. Use arrow functions instead:
this.socket.on('someEvent', (data) => {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.