【发布时间】:2021-11-23 00:02:16
【问题描述】:
我目前正在编写一个 Angular 项目,它打开与 NodeJS 服务器的 websocket 连接。这是服务:
export class WebsocketService {
socket : any;
constructor() { }
setupSocketConnection(){
this.socket = io(environment.SOCKET_ENDPOINT);
this.socket.emit('message', 'The client wants to intruduce itself to the server');
this.socket.on('broadcast', (data: string) => {
console.log(data);
});
}
disconnect() {
if (this.socket) {
this.socket.disconnect();
}
}
}
这是我的组件:
export class AppComponent {
title = '-';
constructor(private websocket : WebsocketService) { }
ngOnInit(){
this.websocket.setupSocketConnection();
}
ngOnDestroy() {
this.websocket.disconnect();
}
}
我的问题是:如何将“数据”从广播事件侦听器传递到组件中以在那里显示?另一项服务将是一个解决方案,但我认为这不是一个好的解决方案。我也可以将监听器放到一个函数中,然后从组件中调用它,但这不会违反服务的封装概念吗?
谢谢
【问题讨论】:
标签: node.js angular typescript websocket socket.io