frontend-tutorial-framework/src/app/services/websocket.service.ts

36 lines
1001 B
TypeScript

// Copyright (C) 2018 Avatao.com Innovative Learning Kft.
// All Rights Reserved. See LICENSE file for details.
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
import { filter, map } from 'rxjs/operators';
import { WebSocketMessage } from '../message-types/websocket-message';
@Injectable()
export class WebSocketService {
private ws: WebSocketSubject<WebSocketMessage>;
constructor() {}
public connect() {
if (!this.ws) {
const wsproto = (location.protocol === 'https:') ? 'wss://' : 'ws://';
const connAddr = wsproto + window.location.host + '/ws';
this.ws = webSocket<WebSocketMessage>(connAddr);
}
}
public observeKey<T extends WebSocketMessage>(key: string): Observable<T> {
return this.ws.pipe(
filter(message => message.key.startsWith(key)),
map(message => <T> message)
);
}
public sendJSON(json: any) {
this.ws.next(json);
}
}