I'm using a basic WebSocket client within Angular 6 application.
Everything works except for some reason both socket.onmessage or socket.addEventListener('message' are fired only once. No errors on console. and the message is defintiely sent to client (correct message is shown in websocket connection frames in browser console). All other events work correctly.
Here is my class to work with websockets:
export class WebsocketService implements OnDestroy {
socket: WebSocket;
constructor(@Inject(APP_CONFIG) private config: IAppConfig, private authService: AuthService) { }
initConnection(): void {
this.socket = new WebSocket(
this.config.apiEndpoint.replace(/^https?:\/\//i, 'ws://') + 'ws/');
this.watchEvent(WSEvent.ERROR).subscribe(data => {
console.log(data);
});
}
watchEvent(wsevent: WSEvent): Observable<any> {
return new Observable(observer => {
this.socket.addEventListener(wsevent, function (event) {
observer.next(event);
});
});
}
onMessage(): Observable<any> {
return new Observable(observer => {
this.socket.onmessage = function (event) {
observer.next(event);
};
});
}
ngOnDestroy() {
// this.socket.close();
}
}
wsevent:
export enum WSEvent {
CLOSE = 'close',
OPEN = 'open',
MESSAGE = 'message',
ERROR = 'error'
}
usage:
this.wsService.watchEvent('message').subscribe((data) => {
console.log(data);
});
this.wsService.onMessage().subscribe((data) => {
console.log(data);
});
In both cases console.log(data); shows me only the first message sent to the client. It doesn't matter how many times the message is sent and the content of the message - onmessage (refering to both options) is fired only once.
Update:
updated this post to contain actually working solution (the issue was that i called observer.complete(); right after observer.next(event); which did what it is supposed to do)
WSEventdefinition. it's just an enum with string keys of ws events. Less than a year later:)this.config.apiEndpointwith your ws server url