I am having trouble converting the JSON response from the websocket server to a TypeScript object. I've been trying to debug it but can't seem to find where the error lies. Can anyone assist me in resolving this issue?
Below is the code snippet for the websocket server:
const wsServer: Server = new Server({port: WEBSOCKET_PORT});
console.log('WebSocket server is listening on port 8085');
export class PushData {
constructor(public push: string,
public workflowId: number) {
}
}
wsServer.on('connection', (websocket, req) => {
websocket.send('This message was pushed by WebSocket server');
websocket.send('Data pushed by server: ');
websocket.on('message', (message) => {
console.log('Server received : %s', message);
const todaysDate = new Date();
// websocket.send('Data pushed by server: ' + todaysDate.toString());
const request1 = new PushData('data', 30);
websocket.send(JSON.stringify(request1));
}
}
Now, moving on to the client Class service:
private faceSubject = new BehaviorSubject<any>(null);
createObservableSocket(url: string): Observable<string> {
this.ws = new WebSocket(url);
return new Observable(
observer => {
this.ws.onmessage = (event) => observer.next(event.data);
this.ws.onerror = (event) => observer.error(event);
this.ws.onclose = (event) => observer.complete();
}
);
}
And finally, here is the client component where I'm attempting to perform the conversion:
ngAfterViewInit(): void {
this.drawOverlayPicture();
// subscribe to the subject
this.subscription = this.wsService.getFaceSubject()
.subscribe((data: PushData) => {
if (data !== null) {
console.log('received data from server', data);
console.log('received data from server push=', data.push);
// var ob = JSON.parse(JSON.stringify(data));
// console.log('received data from server, workflowId=', (<PushData> ob).push);
console.log(this.i++);
}
In my attempts, I always end up with data.push = undefined. Any guidance on how to properly convert the websocket response to an object would be greatly appreciated. Thank you!