This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private connect(): void { | |
this.websocket$ = new WebSocketSubject(this.config); // создаем | |
// если есть сообщения, шлем их в дальше, | |
// если нет, ожидаем | |
// реконнектимся, если получили ошибку | |
this.websocket$.subscribe( | |
(message) => this.wsMessages$.next(message), | |
(error: Event) => { | |
if (!this.websocket$) { |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private reconnect(): void { | |
// Создаем interval со значением из reconnectInterval | |
this.reconnection$ = interval(this.reconnectInterval) | |
.pipe(takeWhile((v, index) => index < this.reconnectAttempts && !this.websocket$)); | |
// Пытаемся подключиться пока не подключимся, либо не упремся в ограничение попыток подключения | |
this.reconnection$.subscribe( | |
() => this.connect(), | |
null, | |
() => { |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public on<T>(event: string): Observable<T> { | |
if (event) { | |
return this.wsMessages$.pipe( | |
filter((message: IWsMessage<T>) => message.event === event), | |
map((message: IWsMessage<T>) => message.data) | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public send(event: string, data: any = {}): void { | |
if (event && this.isConnected) { | |
// костыль с any потому, что на "том" конце ожидается string | |
// более изящный костыль не придумался :) | |
this.websocket$.next(<any>JSON.stringify({ event, data })); | |
} else { | |
console.error('Send error!'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
imports: [ | |
WebsocketModule.config({ | |
url: environment.ws // или просто ссылка в виде 'ws://www.example.com' | |
}) | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
constructor(private wsService: WebsocketService) { | |
this.wsService.on<IMessage[]>('messages') | |
.subscribe((messages: IMessage[]) => { | |
console.log(messages); | |
this.wsService.send('text', 'Test Text!'); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const WS = { | |
ON: { | |
MESSAGES: 'messages' | |
}, | |
SEND: { | |
TEXT: 'text' | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
this.wsService.on<IMessage[]>(WS.ON.MESSAGES) | |
.subscribe((messages: IMessage[]) => { | |
console.log(messages); | |
this.wsService.send(WS.SEND.TEXT, 'Test Text!'); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface IWebsocketService { // публичный интерфейс сервиса | |
addEventListener<T>(topics: string[], id?: number): Observable<T>; | |
runtimeIgnore(topics: string[]): void; | |
runtimeRemoveIgnore(topics: string[]): void; | |
sendMessage(event: string, data: any): void; | |
} | |
export interface WebSocketConfig { // конфиг при DI | |
url: string; | |
ignore?: string[]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class MessageSubject<T> extends Subject<T> { | |
constructor( | |
private listeners: IListeners, // объект с топиками | |
private topic: string, // текущий топик | |
private id: string // id сабжекта | |
) { | |
super(); | |
} |