izupet
izupet

Reputation: 1559

Angular 2 update view on component property change

I created simple WebSocket service and a component and I have a 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 component onNext method is successfully called and console correctly prints fresh data but the view is not getting updated. I even tried with ngZone but with no success.

Upvotes: 2

Views: 1446

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202156

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.

Upvotes: 6

Related Questions