Doing a really simple call to setup connect/stop using SignalR in Angular 6 where I had the following code:
signalR.helper.ts
public static setupHub<T>(hubUrl: string, eventName: string, callback: (data: T) => void, ...params: SignalRParam[]): HubConnection {
const token = localStorage.getItem(appConstant.token);
const url = this.buidlUrl(hubUrl, ...params);
const connection = new HubConnectionBuilder()
.withUrl(url,
{ transport: HttpTransportType.WebSockets, accessTokenFactory: () => token })
.build();
environment.production && connection.start();
!environment.production && connection.start().catch(err => console.error(err.toString()));
connection.on(eventName, callback);
return connection;
}
If I try to login on my page,I keep getting this error on console:
signalR.helper.ts:19 Error: Cannot send data if the connection is not in the 'Connected' State.
I'm new to SignalR and Angular and why I keep getting this error ?
Make sure the promise returned from ".start()" has resolved before invoking any methods. You may want to change your method to return the promise so you can chain other methods off of it. Or switch to using the async/await pattern in the method.
Also, make sure you're not accidentally calling ".stop()". In my case, I had an observable that watched if users were authenticated or not and called ".stop()" if they logged off. The problem was that the observable indicated that the user was not authenticated for a brief moment as the page was loading - which caused a race condition where sometimes it would work and sometimes it would not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With