user93
user93

Reputation: 39

Uncaught (in promise): Cannot send data if the connection is not in the 'Connected' State. while connecting the signalR with angular

While connecting the signalR with angular I am getting the error

Uncaught (in promise): Error: Cannot send data if the connection is not in the 'Connected' State."

and my code is

dashboard.service.ts

private hubConnection: signalR.HubConnection
initWebSocket() {
    this.hubConnection = new signalR.HubConnectionBuilder()
      //.configureLogging(signalR.LogLevel.Debug)
      .withUrl('http://localhost:5000/Notification',{
       skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
      })
      .build();
  this.hubConnection
      .start()
      .then(() => console.log('Connection started'))
      //.then(() => console.log(this.hubConnection.connectionId)
      .catch(err => console.log('Error while starting connection: ' + err))

      const EmailId = "[email protected]";
      this.hubConnection.invoke("Registerd", EmailId);
      console.log("Registered", EmailId);

Can anyone help me to overcome this error

Upvotes: 1

Views: 4818

Answers (1)

Brennan
Brennan

Reputation: 1933

You should read up on Javascript promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

The problem is that you run some code asynchronously (hubConnection.start()) and then without waiting for the result you try to call hubConnection.invoke(...) on the connection which hasn't started yet.

Upvotes: 2

Related Questions