Angular2/Websocket:如何为传入的Websocket消息返回可观察值 [英] Angular2/Websocket: how to return an observable for incoming websocket messages
问题描述
我将使用Angular2接收websocket传入的消息,并根据收到的消息更新网页.现在,我正在使用虚拟echo websocket服务,并将其替换.
I'm going to use Angular2 to receive websocket incoming messages and update a webpage based on those received messages. Right now, I'm using a dummy echo websocket service and will replace it.
据我所知,接收websocket消息的函数必须返回一个Observable,该Observable由将更新网页的处理程序订阅.但是我不知道如何返回一个可观察值.
From my understanding, the function which receive websocket messages has to return an observable that is subscribed by a handler who will update the webpage. But I can't figure out how to return an observable.
代码段附在下面. MonitorService
创建一个websocket连接,并返回一个包含所接收消息的可观察对象.
Code snippet is attached below. The MonitorService
creates a websocket connection and return an observable containing the received messages.
@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();
}
}
下面是另一个组件,该组件订阅从上面返回的可观察对象并相应地更新网页.
Below is another component which subscribes to the observable returned from above and updates webpages correspondingly.
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
Now, I'm running into this error in the browser console
TypeError: this._subscribe is not a function
推荐答案
I put it on a plunker and I added a function for sending message to the Websocket endpoint. Here is the important edit:
public GetInstanceStatus(): Observable<any>{
this.websocket = new WebSocket("ws://echo.websocket.org/"); //dummy echo websocket service
this.websocket.onopen = (evt) => {
this.websocket.send("Hello World");
};
return Observable.create(observer=>{
this.websocket.onmessage = (evt) => {
observer.next(evt);
};
})
.share();
}
更新
正如您在评论中提到的,更好的替代方法是使用Observable.fromEvent()
Update
As you mentioned in your comment, a better alternative way is to use Observable.fromEvent()
websocket = new WebSocket("ws://echo.websocket.org/");
public GetInstanceStatus(): Observable<Event>{
return Observable.fromEvent(this.websocket,'message');
}
Observable.fromEvent()
的
插件示例 ;
此外,您也可以使用WebSocketSubject
进行操作,尽管它似乎还没有准备好(从rc.4开始):
Also, you can do it using WebSocketSubject
, although, it doesn't look like it's ready yet (as of rc.4):
constructor(){
this.websocket = WebSocketSubject.create("ws://echo.websocket.org/");
}
public sendMessage(text:string){
let msg = {msg:text};
this.websocket.next(JSON.stringify(msg));
}
这篇关于Angular2/Websocket:如何为传入的Websocket消息返回可观察值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!