Angular:如何从服务内部的事件中获取数据到我的组件中?



我目前正在写一个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();
}
}

我的问题是:如何传递"data"从广播事件监听器到组件中显示它吗?另一种服务可能是一个解决方案,但我认为它不会是一个好的服务。我也可以将侦听器放入函数中,然后从组件中调用它,但这不会违反服务的封装概念吗?

谢谢

您可以按照以下步骤使用BehaviorSubject:

想象发送一个JSON对象,其中包含一个"类型"字段:确保对使用

发送的数据进行字符串化1-服务器端:

JSON.stringify({type: "message", value: "whatever"})

2-现在是客户端

export class WebsocketService {
// Put the right data type here
message = new BehaviorSubject<string>('');
connection = new BehaviorSubject<string>('');
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) => {
const jsonObject = JSON.parse(data);
switch (jsonObject.type) {
case "message":
this.message.next(jsonObject.value);
break;
case "connection":
this.connection.next(jsonObject.value);
break;
default:
throw new Error('Unknown message type' + jsonObject.type)
break;
}
});
}
disconnect() {
if (this.socket) {
this.socket.disconnect();
}
}
}

另一方面,只需订阅您的数据行为主题发出的值。

export class AppComponent implements OnInit, OnDestroy {
title = '-'; 
subscriptions: Subscription[] = [];
constructor(private websocket : WebsocketService) { }
ngOnInit(){
this.websocket.setupSocketConnection();
this.websocket.message.subscribe(value => {
// Do your stuff here.
console.log(value);
})
this.websocket.connection.subscribe(value => {
// Do your stuff here.
console.log(value);
})
}
ngOnDestroy() {
this.websocket.disconnect();
this.subscriptions.forEach(s => s.unsubscribe());
this.subscription = [];
}
}

最新更新