In my Angular 8 app based on ASP.NET MVC, there is a Dashboard component where I display some kind of statistical data (e.g. sum, average numbers) and I update these data with the help of SignalR after each Create-Update-Delete event by broadcasting new data to all of the clients. On the other hand, I want to build a generic way that should be used throughout the entire app and I think it seems to be good idea to use EventEmitter, BehaviorSubject, Subject, ReplaySubject, etc. in order to pass newly retrieved statistical data to the clients. But there are some kind of differences between these components as indicated on Subject vs BehaviorSubject vs ReplaySubject in Angular, I would like to be clarified on which one is most suitable for the given example? And why?
Note that I need to pass multiple data to the clients across different components that have no parent-child relations (generally between sibling components).
Here is my code when I use EventEmitter. But I think BehaviorSubject might be better for my situation:
service.ts:
@Injectable()
export class SignalRService {
messageReceived = new EventEmitter<ChatMessage>();
connectionEstablished = new EventEmitter<Boolean>();
constructor() {
this.registerOnServerEvents();
this.startConnection();
}
private startConnection(): void {
this._hubConnection
.start()
.then(() => {
this.connectionEstablished.emit(true);
})
}
private registerOnServerEvents(): void {
this._hubConnection.on('ReceiveMessage', (data: any) => {
this.messageReceived.emit(data);
});
}
}
component.ts:
export class ClockComponent {
constructor(private _signalRService: SignalRService, private _ngZone: NgZone) {
this.subscribeToEvents();
}
private subscribeToEvents(): void {
this._signalRService.connectionEstablished.subscribe(() => {
this.canSendMessage = true;
});
this._signalRService.messageReceived.subscribe((message: GetClockTime) => {
this._ngZone.run(() => {
this.allMessages = message;
});
});
}
}