-
Notifications
You must be signed in to change notification settings - Fork 57
/
socket-io.service.ts
66 lines (53 loc) · 2.01 KB
/
socket-io.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { Injectable, EventEmitter, Inject } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import * as io from 'socket.io-client';
import { SocketIoConfig } from './socketIoConfig';
import { SOCKET_CONFIG_TOKEN } from './socket-io.module';
export class WrappedSocket {
subscribersCounter = 0;
ioSocket: any;
constructor(@Inject(SOCKET_CONFIG_TOKEN) config: SocketIoConfig) {
const url: string = config.url || '';
const options: any = config.options || {};
this.ioSocket = io(url, options);
}
on(eventName: string, callback: Function) {
this.ioSocket.on(eventName, callback);
}
once(eventName: string, callback: Function) {
this.ioSocket.once(eventName, callback);
}
connect() {
return this.ioSocket.connect();
}
disconnect(close?: any) {
return this.ioSocket.disconnect.apply(this.ioSocket, arguments);
}
emit(eventName: string, data?: any, callback?: Function) {
return this.ioSocket.emit.apply(this.ioSocket, arguments);
}
removeListener(eventName: string, callback?: Function) {
return this.ioSocket.removeListener.apply(this.ioSocket, arguments);
}
removeAllListeners(eventName?: string) {
return this.ioSocket.removeAllListeners.apply(this.ioSocket, arguments);
}
/** create an Observable from an event */
fromEvent<T>(eventName: string): Observable<T> {
this.subscribersCounter++;
return Observable.create( (observer: any) => {
this.ioSocket.on(eventName, (data: T) => {
observer.next(data);
});
return () => {
if (this.subscribersCounter === 1)
this.ioSocket.removeListener(eventName);
};
}).share();
}
/* Creates a Promise for a one-time event */
fromEventOnce<T>(eventName: string): Promise<T> {
return new Promise<T>(resolve => this.once(eventName, resolve));
}
}