gpt4 book ai didi

websocket - Angular2/Websocket : how to return an observable for incoming websocket messages

转载 作者:太空狗 更新时间:2023-10-29 17:09:46 28 4
gpt4 key购买 nike

我将使用 Angular2 接收 websocket 传入消息并根据这些接收到的消息更新网页。现在,我正在使用虚拟 echo websocket 服务并将替换它。

根据我的理解,接收 websocket 消息的函数必须返回一个由将更新网页的处理程序订阅的可观察对象。但我不知道如何返回一个可观察对象。

代码片段附在下面。 MonitorService 创建一个 websocket 连接并返回一个包含接收到的消息的可观察对象。

@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();
}

}

下面是另一个组件,它订阅从上面返回的可观察对象并相应地更新网页。

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 不是函数

最佳答案

我把它放在 plunker 上我添加了一个将消息发送到 Websocket 端点的函数。这是重要的编辑:

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()

websocket = new WebSocket("ws://echo.websocket.org/");
public GetInstanceStatus(): Observable<Event>{
return Observable.fromEvent(this.websocket,'message');
}

plunker example对于 Observable.fromEvent();

此外,您可以使用 WebSocketSubject 来完成它,尽管它看起来还没有准备好(从 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));
}

plunker example

关于websocket - Angular2/Websocket : how to return an observable for incoming websocket messages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36851347/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com