is it somehow possible to listen to a WebSocket inside a service, and make that service "reactive" by listening to messages from sockets and then sending the changes to my other components, e.g by observables?
It should of course work over different tab/browser instances.
What is the correct pattern? And if I use the service in another angular component, do I need to somehow initialize it first, or is it enough to import the dependency inside my component, because there is no ngOnInit
method in services?
I would probably create my socket listener in the service constructor and then next new events with observables. But, not sure exactly how.!
For any library raising events outside angular's scope/zone the best bet is to bring it into the scope/zone.
This way you don't need to think about any further synchronization with angular lifecycle events.
I usually use a Subject or ReplaySubject in a service to make sure all components can listen to the events raised.
@Injectable()
export class YourService {
eventType1$ = new Subject()
constructor(private ngZone: NgZone ...
...
socketObject.onEventType1((eventType1) => {
this.ngZone.run(() => {
this.eventType1$.next(eventType1)
});
})
Then from your components you can subscribe to this service's public observable normally:
yourComponentFunction() {
this.yourService.eventType1$.subscribe((eventType1) => {
// do something with eventType1
})
}
Note: please remember to complete any subscriptions when the component is destroyed to avoid the common memory leak.