I recently set up a WebSocket service and component, but I'm facing challenges with updating the view when new data is received through the WebSocket connection.
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('connection opened');
);
}
}
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('subscription completed');
});
}
}
runners-list.html
<h1>{{output}}</h1>
Although the onNext method in the component successfully receives fresh data and logs it to the console, the view does not update accordingly. I even attempted using ngZone without success.