I have multiple Angular
components that are subscribing to a SignalR
hub connection. I have wrapped the SignalR
hub connection object to an angular service, hubconnection.service.ts
:
import { Injectable } from '@angular/core';
import { HubConnectionBuilder, HubConnection } from '@aspnet/signalr';
@Injectable()
export class HubConnectionService {
public MyHubConnection: HubConnection;
constructor() {
this.MyHubConnection = new HubConnectionBuilder()
.withUrl('/sensorHub')
.build();
this.MyHubConnection
.start()
.then(() => console.log('[HubConnectionService] Connection started'))
.catch(err => console.log('[HubConnectionService] Error while starting connection: ' + err));
}
}
Now I have a component from where I want to subscribe to the data received through the SignalR
hub, to do this I import my SignalR
wrapper, and in the constructor I call the .on()
method. To unsubscribe from that event I call the .off()
method in the destructor:
export class RawdataComponent implements OnInit {
constructor(private hubConnectionService: HubConnectionService) { }
ngOnDestroy() {
this.hubConnectionService.MyHubConnection.off('Broadcast');
}
ngOnInit() {
this.hubConnectionService.MyHubConnection.on('Broadcast',
function(sender, message) {
console.log('New message received: ' + message);
});
}
}
When I initially access the page that is described by this component, everything works as expected (console.log()
is logging for every message I receive).
When I leave the page, MyHubConnection.off('Broadcast');
is called. Then after I access the previous page again, the constructor is called and another subscription is made, but the previous one is not closed, and I get two console.log()
calls.
Where's the mistake I'm making? Shouldn't MyHubConnection.off('Broadcast');
close the current subscription when I leave the page?