• 并且需要用websocket实时接收数据 VS 组件ng2websocket的


     

    chart.service.ts:

    import { Injectable } from '@angular/core';
    import { WebSocketService } from './websocket.service';
    import 'rxjs/add/operator/map';
    @Injectable()
    export class ChatService{
      public ddd=[]; //收集websocket传递过来的值
      constructor(
        private wsService01: WebSocketService) {}
      onAAA(a01):void{
        const URL01 = 'ws://--websocket地址--jsessionid=?id='+a01;
        const NODEID01 = '{id:' + a01 + '}';
        this.wsService01
        .create(URL01,NODEID01)
        .map((response: MessageEvent): string => {        
            let data = response.data;        
            return data;      
        })      
        .subscribe(msg => {        
            let data=eval('('+msg+')');        
            this.ddd.push(data);      
        });  
      }
    }

    websocket.service.ts:

    import {Injectable} from '@angular/core';
    import {Observable} from 'rxjs/Observable';
    import {Subject} from 'rxjs/Subject';
    import {Observer} from "rxjs/Observer";
    @Injectable()
    export class WebSocketService {
      public a01:any;
      public create(url: string,nodeid:string): Subject<MessageEvent> {
        let ws = new WebSocket(url);
        ws.onopen = function() {
          ws.send(nodeid);
      };
        // 如果想要断开websocket连接,调用websocket.service.ts的a01函数即可。
        // this.a01 = function() {
        //   ws.close();
        //   console.log("websocket01已经断开连接");
        // };
        let observable = Observable.create(
          (obs: Observer<MessageEvent>) => {
            ws.onmessage = obs.next.bind(obs);
            ws.onerror   = obs.error.bind(obs);
            ws.onclose   = obs.complete.bind(obs);
            return ws.close.bind(ws);
          });
        let observer = {
          next: (data: Object) => {
            if (ws.readyState === WebSocket.OPEN) {
              ws.send(data);
            }
          }
        };
        return Subject.create(observer, observable);
      }
    }
  • 相关阅读:
    转载Dockerfile 中 RUN, CMD, ENTRYPOINT 的区别
    在linux上通过ssh使用github
    dns服务
    centos6 free 和 centos 7的free 的差异与对比
    无重复字符的最长子串
    go get命令在go mod目录下与正常目录执行的区别
    安装git
    转载 筛子算法之golang实现求素数解析
    Go语言基础之并发
    go之无缓冲channel(通道)和有缓冲channel(通道)
  • 原文地址:https://www.cnblogs.com/jayruan/p/7758313.html
Copyright © 2020-2023  润新知