Data transmission is only possible when the connection is in the 'Connected' state

Trying to set up a simple connection using SignalR in Angular 6, I wrote 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;
}

However, when trying to log in on my page, I keep encountering this error message in the console:

signalR.helper.ts:19 Error: Cannot send data if the connection is not in the 'Connected' State.

I'm relatively new to SignalR and Angular. Can someone explain why I am getting this error?

Answer №1

Before proceeding, it is crucial to ensure that your connection has been initiated successfully

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chathub")
    .configureLogging(signalR.LogLevel.Information)
    .build();

async function start() {
    try {
        await connection.start();
        console.log("SignalR Connected.");
    } catch (err) {
        console.log(err);
        setTimeout(start, 5000);
    }
};

connection.onclose(async () => {
    await start();
});

// Begin the connection process.
start();

Answer №2

It is essential to ensure that the promise returned by ".start()" has been resolved before executing any other methods. Consider modifying your method to return the promise for better chaining capabilities, or opt for utilizing the async/await pattern within the method.

Additionally, be cautious of inadvertently invoking ".stop()". I encountered a situation where an observable monitored user authentication status and triggered ".stop()" upon logout. The issue arose when the observable briefly indicated user non-authentication during page loading, leading to a potential race condition resulting in intermittent success and failure.

Answer №3

To ensure SignalR functions correctly, make sure to include the necessary scripts in your code. This includes adding the following lines to your *.cshtml file:

<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>

If you do not navigate to a page with these script tags, SignalR will not be able to create the Hub. To have it available throughout the web app, consider placing the scripts in _Layout.cshtml.

Failure to include these scripts may result in errors like the following:

POST http://myserver.com/chatHub/negotiate 404 (Not Found)
(anonymous) @ XhrHttpClient.ts:84
XhrHttpClient.send @ XhrHttpClient.ts:30
Utils.ts:179 [2019-06-14T19:21:39.774Z] Error: Failed to complete negotiation with the server: Error: Not Found
ConsoleLogger.log @ Utils.ts:179
Utils.ts:179 [2019-06-14T19:21:39.774Z] Error: Failed to start the connection: Error: Not Found
Error: Cannot send data if the connection is not in the 'Connected' State.

For more information and resources on SignalR, please refer to the following links:

Overview: https://learn.microsoft.com/en-us/aspnet/core/signalr/introduction?view=aspnetcore-2.2

Hubs: https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-2.2

Clients: https://learn.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-2.1#call-hub-methods-from-client

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create collaborative documents with serverless TypeScript extension

Utilizing Amazon Lambda AWS along with Serverless and the Serverless Plugin TypeScript to develop my TypeScript files has been quite a challenge. I have implemented shared code in my project, organized within folders such as: /shared: shared1.ts, shared2. ...

What is the best way to terminate a Node.js app using a scheduler?

I've been attempting to halt my cron task and shut down the entire nodeapp after 5 executions, but despite trying various methods, all attempts have failed. The message "time to quit" continues to appear in the log every minute. What would be the mos ...

Angular2 can enhance your webpage with a <div> element that covers the entire screen

While working on my Angular2 application, I encountered a challenging issue that I can't seem to resolve or find a solution for. Take a look at this image of my page: https://i.stack.imgur.com/b6KlV.png Code: content.component.html <app-header& ...

The blur event in Angular Material's mat-date-range-input does not trigger if the End Date is not selected

I am currently utilizing Angular 15 along with Angular Material 14. The code for the DatePicker control is shown below. <mat-form-field class="datepicker-widget" appearance="fill"> <mat-date-range-input [formGroup]="d ...

The index type '{id:number, name:string}' is not compatible for use

I am attempting to generate mock data using a custom model type that I have created. Model export class CategoryModel { /** * Properties */ public id : number; public name : string; /** * Getters */ get Id():number{ return this.id; ...

When restarting nginx, Angular fails to display the index page

On my VPS server, I have an application with the backend coded in node.js and the frontend in Angular. After restarting nginx, I encountered some issues where my API stopped working on HTTPS and only functioned on HTTP (previously, I was able to make requ ...

Generate a unique Object URL for the video source by utilizing the binary string obtained from the backend

I've been facing an issue with loading binary video data from my backend using fastAPI. When I curl the endpoint and save the file, it plays perfectly fine on my laptop. For the frontend, I'm using React+Typescript. I fetch the binary video data ...

How come the index variable doesn't show the index in *ngFor loop in Angular 2?

When working with ng-repeat in Angular 1 to display the index, this code is used: <div ng-repeat="car in cars"> <ul> <li>Index: {{$index+1}}</li> <li>Car Name:{{car.name}}</li> </ul> </div> However, w ...

The Angular Component I've created is displaying a single set of data on each mat-tab screen

I have developed a component with the file name hukamnama-sahib.component.html, which looks like this: <body *ngFor="let dataitem of HukamnamaSahibList"> <h4> <span class="gurmukhi">{{dataitem.line.gurmukhi.unico ...

Unable to iterate over a JSON response from a POST request in Angular 8

I am attempting to iterate through a JSON object that is returned after making a POST request to my REST API. However, I'm encountering the following error: DatetodateComponent.html:33 ERROR Error: Cannot find a differ supporting object '[objec ...

Tips for crafting a test scenario for input alterations within Angular

Hello there, currently I am working on an application using Angular and TypeScript. Here is a snippet of my template code: <input type="text" placeholder="Search Results" (input)="searchInput($event)"> And here is the TypeScript code for the searc ...

The issue of "Invalid arguments passed to jsPDF.text" encountered while using jsPDF on an nginx server

In my project admin, I have successfully implemented jspdf. The admin panel works perfectly fine on localserver. However, when I deploy it to a live nginx server, the server side throws an error: Error: Uncaught (in promise): Error: Invalid arguments passe ...

I am encountering difficulties in accessing my component's property within the corresponding template while working with Angular 5

When I call an HTTP POST method to retrieve table names from the backend, I attempt to display them in the template using ngFor. However, the table names are not appearing on the screen. The tNames property is inaccessible in the template. As a beginner i ...

Tips for extracting specific JSON response data from an array in TypeScript

I have an array named ReservationResponse, which represents a successful response retrieved from an API call. The code snippet below demonstrates how it is fetched: const ReservationResponse = await this.service.getReservation(this.username.value); The st ...

Issues arise when attempting to override attributes within the HTML of a parent component in Angular

Why does overriding an attribute in a child class that extends from another not work as expected? Here's a made-up scenario to simplify the issue: Parent class file: gridbase.component.ts import { Component, OnInit } from '@angular/core'; ...

Set the value obtained from a resolved promise to a mutable reference object in a React component

I am in the process of developing a random movie generator. I am utilizing an external API to retrieve a list of movies and then selecting one randomly from the returned data. The current implementation is as follows: export default function Page() { con ...

What is the process for assigning a serial number to each row in the MUI DataGrid?

Initially, the server is accessed to retrieve some data. After that, additional data is added. While the data does not contain an ID, the form must still display a serial number. const columns: GridColDef[] = [ { field: 'id' ...

Utilize the failure of Travis due to issues with a Git submodule to improve

I am facing an issue with my Angular project that has a git submodule for the backend. When I build the project on my local machine, it is successful. However, when I try to build it on Travis, it fails. npm ERR! enoent ENOENT: no such file or directory, ...

When organizing data, the key value pair automatically sorts information according to the specified key

I have created a key value pair in Angular. The key represents the questionId and the value is the baseQuestion. The baseQuestion value may be null. One issue I am facing is that after insertion, the key value pairs are automatically sorted in ascending ...

Types of Axios responses vary depending on their status codes

I am looking to create a specific type for axios responses based on the status code: types: type SuccessfulResponseData = { users: .... }; interface SuccessfulResponse extends AxiosResponse<SuccessfulResponseData, any> { status: 200; } ty ...