angular - 在 Angular 6 中使用网络套接字

标签 angular websocket angular6

我正在尝试从网络套接字获取数据。我正在将 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/

相关文章:

css - primeNg DataTable 单元格中的溢出文本

javascript - 如何使用 Websockets 连接到 MQTT Broker?

angular - 重置动态添加的字段值

typescript - 类型 'FormArray' 不可分配给类型 'any[]' 。类型 'includes' 中缺少属性 'FormArray'。在angular6 typescript 中

javascript - JSObjects如何动态访问 child

angular - 如何在没有 *ngIf 的情况下渲染 ng-container 或 ng-template?

android - Ionic 5 Phonegap-NFC 插件安装时未安装错误

javascript - 未捕获的类型错误 : Cannot read property of 'send' undefined

php - 增加php websocket最大连接数

typescript - 你如何使用 rxjs 6 对 Angular 6 中的 Observable<Item[]> 进行排序?