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

40 lines
1.2 KiB
TypeScript

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");
if (window.location.protocol === 'https:' && url.indexOf(INSECURE) === 0) {
url = SECURE + url.substr(INSECURE.length);
}
this.websocket = new WebSocket(url);
setInterval(() => {
let msg = { "topic": "heart-beat", "message": "" };
this.websocket.send(JSON.stringify(msg));
}, 30000);
return new Observable(ob => {
this.websocket.onopen = () => {
console.log('websocket was connected...')
}
this.websocket.onmessage = (event) => {
ob.next(event.data)
}
this.websocket.onerror = () => {
ob.error("连接失败")
}
this.websocket.onclose = () => {
console.log('websocket was complete')
ob.complete();
}
})
}
}