我正在尝试从网络套接字获取数据。我正在将 websocket 对象初始化为全局。
socket =new WebSocket('ws://xx.xx.xx.xx:xxxx/socket');
在 ngOnInit 上,我打开连接:
this.socket.onopen = function(){
console.log("websocket is open now");
}
现在我需要使用从 UI 触发的函数发送消息,并且来自 websocket 的回复应将消息存储在全局变量中。
sampleFunction(val) {
this.socket.send(val);
this.socket.onmessage=function(event){
console.log("got message");
this.dummy=event.data;
}.bind(this)
}
因此,在页面加载时,它正在连接,但是当我触发该函数时,消息不会消失,因此我没有收到任何响应
最佳答案
我正在使用 Angular 附带的 rxjs 及其 webSocket 方法。
import {webSocket} from 'rxjs/webSocket';
socket = webSocket(`${environment.serviceWebSockets}/api`);
constructor(){
// now you can subscribe to messages wherever in your code
this.socket.subscribe(message => {
console.log(message); // or just use it directly
}, error => {
console.error(error); // handle errors
});
}
通过此 webSocket 发送数据:
socket.next(JSON.stringify({some:"data"}));
用于连接使用:
socket.subscribe();
断开连接:
socket.complete();
有关 https://rxjs-dev.firebaseapp.com/api/webSocket/webSocket 的更多信息
关于angular - 在 Angular 6 中使用网络套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55392159/