当我将响应json从websocket服务器转换为ts对象时,我有一个基本问题,但我找不到错误在哪里... 你能帮忙解决一下吗?
这是websocket服务器:
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));
}
}
这是客户 班级服务:
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();
}
);
}
这里是客户端组件,我想进行转换:
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++);
}
和
export class PushData {
constructor(public push: string, public workflowId: number) {}
}
这里我总是te data.push = undefined。 你能告诉我如何将websocket响应转换为对象吗?
答案 0 :(得分:1)
编辑: 服务器只在从客户端收到消息时才会推送PushData对象,但是他会在连接时向客户端发送两个字符串。这就是为什么你得到data.push是未定义的,因为数据只是字符串。
websocket.send('This message was pushed by WebSocket server');
websocket.send('Data pushed by server: ');
您需要从客户端发出消息才能接收pushData对象!