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);
  }
}
 posted on 2017-10-30 23:39  jayruan  阅读(819)  评论(0编辑  收藏  举报