Issue
I am currently writing an angular project that opens a websocket connection with a NodeJS server. This is the service:
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();
}
}
}
and this is my component:
export class AppComponent {
title = '-';
constructor(private websocket : WebsocketService) { }
ngOnInit(){
this.websocket.setupSocketConnection();
}
ngOnDestroy() {
this.websocket.disconnect();
}
}
My question is: how can I pass "data" from the broadcast event listener into the component to display it there? Another service would be a solution, but I dont think it would be a good one. I could also put the listener into a function and call it from the component, but wouldn't that violate the encapsulation concepts of services?
Thank you
Solution
You could use BehaviorSubject by following theses steps:
Imagine sending JSON object holding a "type" field: Make sure to stringify data sent using
1- Server side:
JSON.stringify({type: "message", value: "whatever"})
2- Now client side
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();
}
}
}
And on there other hand, just subscribe to your data behaviorSubject emited values.
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 = [];
}
}
Answered By - millenion
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.