Created
January 17, 2019 08:08
-
-
Save RobertPaulson90/5b82949034021c1e496495dedb916eb0 to your computer and use it in GitHub Desktop.
Angular reconnect for SignalR Core js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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