Skip to content

Instantly share code, notes, and snippets.

@binaryPUNCH
Created January 17, 2019 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binaryPUNCH/5b82949034021c1e496495dedb916eb0 to your computer and use it in GitHub Desktop.
Save binaryPUNCH/5b82949034021c1e496495dedb916eb0 to your computer and use it in GitHub Desktop.
Angular reconnect for SignalR Core js
import { Component, OnInit, OnDestroy } from "@angular/core";
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';
@Component({
selector: "app-my",
templateUrl: "./my.component.html",
styleUrls: ["./my.component.scss"],
})
export class MyComponent implements OnInit, OnDestroy {
private hubConnection: HubConnection;
constructor() {
}
ngOnInit(): void {
this.startSignalRAsync().then(() => {
// You can invoke some method with this.hubConnection.invoke().
});
}
ngOnDestroy(): void {
// You should remove event handlers with this.hubConnection.off().
this.hubConnection.stop();
}
private startSignalRAsync(): Promise<void> {
let hubBuilder = new HubConnectionBuilder();
this.hubConnection = hubBuilder.withUrl(SignalRHubUrl).build();
// You can attach event handlers with this.hubConnection.on().
this.hubConnection.onclose(async (error) => {
if (error !== undefined) {
// You can implement logic for error loging.
}
await this.reconnectSignalRAsync();
});
return this.hubConnection.start();
}
private async reconnectSignalRAsync(): Promise<void> {
let shouldRetryToConnect = true;
while (shouldRetryToConnect) {
try {
await this.startSignalRAsync();
// You can invoke some method with this.hubConnection.invoke().
shouldRetryToConnect = false;
}
catch (e) {
// You can implement logic for maximum retries.
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment