izupet izupet - 4 months ago 49
AngularJS Question

Angular 2 update view on component property change

I created simple WebSocket service and a component and i have hard time updating view when new data is received through websocket.

websocket.service.ts

import {Injectable} from "angular2/core";
import {Observable} from 'rxjs/Observable';

@Injectable()
export class WebsocketService {

observable: Observable;
websocket = new WebSocket('ws://angular.local:8080');

constructor() {
this.observable = Observable.create(observer =>
this.websocket.onmessage = (msg) => observer.next(msg);
this.websocket.onopen = (msg) => console.log('openned');

);
}
}


runner.component.ts

import {Component} from "angular2/core";
import {WebsocketService} from "./websocket.service";

@Component({
selector: "runners-list",
templateUrl: "../partials/runners-list.html",
providers: [WebsocketService],
styleUrls: ["../css/app.css"]
})

export class RunnerComponent {

output: any;

constructor(private _websocketService: WebsocketService) {
_websocketService.observable.subscribe(
function onNext(data) {
this.output = data;
console.log(this.output);
},
function onError(error) {
console.log(error);
},
function onCompleted() {
console.log('completed');
});
}
}


runners-list.html

<h1>{{output}}</h1>


In componenet onNext method is successfully called and console correctly prints fresh data but view is not getting updated. I even tried with ngZone but with no success.

Answer

You should use arrow functions for your callbacks to be able to use lexical this:

constructor(private _websocketService: WebsocketService) {
    _websocketService.observable.subscribe(
        (data) => {
            this.output = data;
            console.log(this.output);
        },
        (error) => {
            console.log(error);
        },
        () => {
            console.log('completed');
    });
}

In your case, this doesn't correspond to the instance of the component...

See this link for more hints about the lexical this of arrow functions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions.

Comments