Reputation: 943
I have a basic problem when i convert the response json from the websocket server to a ts object, but i cannot find where is the error... Can you help to fix it, please?
Here is 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));
}
}
Here is 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 here is client component where i want to do the convert:
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++);
}
and
export class PushData {
constructor(public push: string, public workflowId: number) {}
}
Here i got always te data.push = undefined. Can you tell me how to convert the websocket response to object, please?
Upvotes: 0
Views: 358
Reputation: 3945
EDIT : The server will only push a PushData object when he receives a message from client, but he will send two string to the client on connection. This is why you get data.push is undefined, because data is only strings.
websocket.send('This message was pushed by WebSocket server');
websocket.send('Data pushed by server: ');
You need to emit a message from the client in order to receive the pushData object !
Upvotes: 1