I have a component A that handles a WebSocket. And in that I also have multiple components for presentation (e.g. B). When the WebSocket gets a specific message I need to do an action in a specific component (e.g. reload data).
The way I do this is having a subject in A. This is passed into B. When the WebSocket in A gets a message I call "next" to trigger B.
A.component.ts
subj : Subject <string> = new Subject <string> ();
connectWebsocket ()
{
let sjs = new SockJS ("http://localhost:8090/ep");
this.sc = Stomp.over (sjs);
this.sc.connect ({}, (frame) =>
{
this.sc.subscribe ("/broker/webclient", (event) =>
{
if (event.body == "RELOAD")
{
this.subj.next ("RELOAD"); // trigger B to reload
}
});
}
}
B.component.ts
@Input () subj : Subject <string>;
ngOnInit ()
{
this.subj.subscribe
(
(msg) =>
{
// reload data if msg == "RELOAD"
}
);
}
Its working well. But I am not sure if it is common strategy to do that or are there better ways (e.g. reload in A and pass only the data to B - or using another mechanism)?