I have implemented a basic WebSocket client in an Angular 6 application.
Everything seems to be working fine, except for the fact that both socket.onmessage
and
socket.addEventListener('message'
are only triggered once. There are no errors in the console, and the correct message is being received by the client (verified through websocket connection frames in the browser console). All other events work as expected.
Below is my WebsocketService class:
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);
});
Upon testing, I noticed that both console.log(data);
statements only display the first message sent to the client, regardless of how many times or what content is sent - the onmessage
event is triggered only once.
Update:
I have updated this post with a solution that actually works. The issue was due to calling observer.complete();
immediately after observer.next(event);
, which prematurely ended the stream.