0

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.

1 Answer 1

6

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) => {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.