How to monitor SignalR ConnectionState in Angular 11 after SignalR connection is established continously

Viewed 76

I am trying to find a way to monitor a SignalR connection continuously like say every minute or every 3 minutes. Trying to find a way to check the connection state. Do I need to set up an observable that can be subscribed to. But then that would have to be in a Component or do I do that in the app.Module or app.component ? Is it connection.OnClose();

the Angular Code in my SignalR Service class is:

 Injectable({
 providedIn: 'root'
})
export class SignalrService {
 connection: signalR.HubConnection;
  
 constructor() {
   this.connection = new signalR.HubConnectionBuilder()
   .withUrl(environment.hubAddress)
   .build();
   this.connect();
 }
  
 public connect() {
   if (this.connection.state === signalR.HubConnectionState.Disconnected) {
     this.connection.start().catch(err => console.log(err));
   }
 }
  
 public getMessage(next) {
     this.connection.on('SendMessage', (message) => {
       next(message);
     });
 }
  
 public disconnect() {
   this.connection.stop();
 }
}
1 Answers

I was able to solve this by checking connection reconnecting(), reconnected() and onClose()events:

    constructor() {
   this.connection = new signalR.HubConnectionBuilder()
   .withUrl(environment.hubAddress)
   .build();
   
    this.connection.reconnecting() => {}
this.connection.reconnected() => {}
    this.connection.onClose() => {}

    this.connect();
 }
Related