【发布时间】:2016-08-19 11:31:18
【问题描述】:
我将使用 Angular2 接收 websocket 传入消息并根据收到的消息更新网页。现在,我正在使用一个虚拟的 echo websocket 服务,并将替换它。
据我了解,接收 websocket 消息的函数必须返回一个由处理程序订阅的可观察对象,该处理程序将更新网页。但我不知道如何返回一个 observable。
代码sn-p附在下面。 MonitorService 创建一个 websocket 连接并返回一个包含接收到的消息的 observable。
@Injectable()
export class MonitorService {
private actionUrl: string;
private headers: Headers;
private websocket: any;
private receivedMsg: any;
constructor(private http: Http, private configuration: AppConfiguration) {
this.actionUrl = configuration.BaseUrl + 'monitor/';
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
}
public GetInstanceStatus = (): Observable<Response> => {
this.websocket = new WebSocket("ws://echo.websocket.org/"); //dummy echo websocket service
this.websocket.onopen = (evt) => {
this.websocket.send("Hello World");
};
this.websocket.onmessage = (evt) => {
this.receivedMsg = evt;
};
return new Observable(this.receivedMsg).share();
}
}
下面是另一个组件,它订阅从上面返回的 observable 并相应地更新网页。
export class InstanceListComponent {
private instanceStatus: boolean
private instanceName: string
private instanceIcon: string
constructor(private monitor: MonitorService) {
this.monitor.GetInstanceStatus().subscribe((result) => {
this.setInstanceProperties(result);
});
}
setInstanceProperties(res:any) {
this.instanceName = res.Instance.toUpperCase();
this.instanceStatus = res.Status;
if (res.Status == true)
{
this.instanceIcon = "images/icon/healthy.svg#Layer_1";
} else {
this.instanceIcon = "images/icon/cancel.svg#cancel";
}
}
}
现在,我在浏览器控制台中遇到了这个错误
TypeError: this._subscribe is not a function
【问题讨论】:
标签: websocket angular observable