Files
airport-chengdu-web/src/app/services/websocket.service.ts
T

40 lines
1.2 KiB
TypeScript
Raw Normal View History

2018-11-29 10:40:23 +08:00
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
var INSECURE = 'ws://';
var SECURE = 'wss://';
@Injectable()
export class WebsocketService {
public websocket: WebSocket;
constructor() { }
dynamicsMessage() {
let url = ("ws://" + window.location.host + "/v2/broker/?topics=schd,msg");
2018-11-29 10:40:23 +08:00
if (window.location.protocol === 'https:' && url.indexOf(INSECURE) === 0) {
url = SECURE + url.substr(INSECURE.length);
}
this.websocket = new WebSocket(url);
2018-12-20 15:45:20 +08:00
setInterval(() => {
let msg = { "topic": "heart-beat", "message": "" };
this.websocket.send(JSON.stringify(msg));
}, 30000);
2018-11-29 10:40:23 +08:00
return new Observable(ob => {
this.websocket.onopen = () => {
console.log('websocket was connected...')
}
this.websocket.onmessage = (event) => {
2018-12-12 18:27:21 +08:00
ob.next(event.data)
2018-11-29 10:40:23 +08:00
}
this.websocket.onerror = () => {
ob.error("连接失败")
}
this.websocket.onclose = () => {
2018-12-03 11:28:24 +08:00
console.log('websocket was complete')
2018-11-29 10:40:23 +08:00
ob.complete();
}
})
}
}