基于Angular4的前端WebSocket实现方式的更换
2017-11-07 本文已影响0人
环零弦
之前用的是好不容易找到的一个日本人写的Angular4
的WebSockert
组件,名字叫simple-ng-websocket
,但是据有人说在刚出的Angular5
中这个组件不能正常工作,所以就又调研其它替代方案,后来发现Angular4+
中可以直接使用Websocket
,并不需要另外引入其它组件。本文几乎抄自《前端 - Angular2与websocket结合使用》。
from 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);
});
}
}
from 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);
}
}
在业务类中的构造器中将webSocket实例传入,另外在app.module.ts
中将其写入providers
即可。