Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot send data if the connection is not in the 'Connected' State

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 ?

like image 674
hafizi hamid Avatar asked Dec 21 '18 03:12

hafizi hamid


1 Answers

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.

like image 102
adam0101 Avatar answered Nov 01 '22 13:11

adam0101