我创建了简单的WebSocket服务和组件,当通过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');
});
}
}
亚军list.html
<h1>{{output}}</h1>
在组件onNext方法成功调用并且控制台正确打印新数据但视图未更新。我甚至尝试过使用ngZone但没有成功。
你应该使用箭头函数为你的回调能够使用词法this
:
constructor(private _websocketService: WebsocketService) {
_websocketService.observable.subscribe(
(data) => {
this.output = data;
console.log(this.output);
},
(error) => {
console.log(error);
},
() => {
console.log('completed');
});
}
在您的情况下,this
不对应组件的实例...
有关箭头函数词汇的更多提示,请参阅此链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions。