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)?
CodePudding user response:
I think your approach is not "idiomatic" in Angular.
What is usually considered best practice is the following:
- create a service that exposes 2 types of APIs
- normal methods that the clients of the service can use to issue commands
- Observable streams for clients which need to subscribe to them
- pass the service to the components that need to use it via dependency injection
In your case the service should have probably something like this:
- a method to start the connection with the websocket server (or maybe this connection is established at initialization of the service)
- a private subject that you
next
when the appropriate message is received from the websocket service - a public Observable that you obtain executing the method
asObservable()
on the private subject
B.component.ts
would receive the service via dependency injection and would subscribe to the public Observable exposed by the service.
This idea is described in details in this article. Even if the article show an example in React, the concepts of Service and Component can be mapped one to one with those of Angular.