My attempt at creating a web-socket-client involved organizing all server messages into a BehaviorSubject. Here's the snippet of code:
export class WebSocketConnectionService {
public ResponseList: BehaviorSubject<WebSocketResponse> = new BehaviorSubject(null);
private socket: any;
private webAuth: Auth;
private pingInterval: any;
constructor(private authService: AuthService) {
this.authService.UserToken.subscribe(myToken => {
const myUUID = this.authService.getUUID();
this.webAuth = {token: myToken, uuid: myUUID};
console.log('Auth: ', this.webAuth);
});
this.ResponseList.subscribe(response => {
console.log('New Response in List: ', response);
})
this.socket = new WebSocket(environment.socket_url);
this.socket.onmessage = this.onMessage;
console.log('Socket: ', this.socket);
}
private onMessage(message: MessageEvent) {
const body: WebSocketResponse = JSON.parse(message.data);
console.log('Message: ', message);
console.log('data: ', body);
console.log('list: ', this.ResponseList);
this.ResponseList.next(body);
}
public sendConnection(user: UserItem): Promise<any> {
return new Promise((resolve, reject) => {
try {
this.sendInternalCommand('link_user', user);
resolve();
} catch(e) {
console.error(e);
reject();
}
})
}
private sendInternalCommand(command: string, data: any) {
const message: WebSocketConnectionItem = {
version: 1,
event: command,
auth: this.webAuth,
body: data
};
const string_message = JSON.stringify(message);
console.log('Send: ', string_message);
this.socket.send(string_message);
}
}
I managed to successfully send the open ConnectionItem. However, I encountered an issue in onMessage where the object ResponseList turns out to be null.
What could possibly be the problem here?
Your assistance will be greatly appreciated.