SingalR is a library which helps us provide a real-time web functionality to our applications. This means that our server can push data to any connected client as soon as that data is provided, in a real-time, and vice verse.

In this article, we are going to show you how to use SignalR with .NET Core and Angular through the practical example.

We are going to simulate a real-time data flow by using the Timer class in .NET Core and use that data to change states of our Angular charts in real time as well. For this example, we are going to use only one-way communication (from the server to the client), but we will add an additional feature to the example, to show the two-way communication as well (client-server-client).

So, without further ado, let’s get started.

If you want to download a finished project, you can clone the repo from Real-Time Charts SignalR source code.

This article is divided into the following sections:

Creating Projects and Basic Configuration

First thing first.

Let’s create both the .NET Core and Angular projects. We are going to name them RealTimeCharts_Server and RealTimeCharts_Client respectively. For the .NET Core project, we are going to choose 2.1 version Web API empty project and for the Angular side, we are creating Angular version 7 with no routings created and CSS for the styles.

As soon as projects are created, we are going to switch to the server side project and set up some basic configuration. To do that, let’s open the launchSettings.json file and modify it accordingly:

Our server-side project will run on localhost:5001 and the client side will run on localhost:4200, so in order to establish communication between those two, we need to enable CORS. Let’s open the Startup.cs class and modify it:

That is it regarding the configuration. Let’s move on to the next part.

SignalR Installation, Hub and Configuration

The SignalR library is already installed in the .NET Core project as a part of the Microsoft.AspNetCore.App package, but we need to install it for the client side. To do that, we are going to open the Angular project in Visual Studio Code and type the following command in the terminal window:

InstallingSignalR - SignalR with .NET Core and Angular

That is it for now regarding the client side.

Let’s switch back to the server side project and create a new folder Models. In that folder, we are going to create a new class ChartModel and modify it:

This form of data is expected by the Angular Charts library (which is yet to be installed), thus the model properties Data and Label.

Having the model prepared, we are going to continue by creating a new folder HubConfig and inside a new class ChartHub:

As we can notice, our ChartHub class must derive from the Hub class, which is a base class for the SignalR hub. But why do we need this ChartHub?

Well, a Hub is a high-level pipeline that allows communication between client and server to call each others methods directly. So basically, a Hub is a communication foundation between client and server while using SignalR.

Right now our ChartHub class is empty because we don’t need any methods inside it, yet.

To complete the SignalR configuration, let’s modify the Startup.cs class again:

In the Configure method, we are adding SignalR to the IService collection. And in a ConfigureServices method, we are adding SignalR to the request pipeline by pointing to our ChartHub with the provided /chart path.

Timer Implementation with DataManager and ChartController

To simulate a real-time data flow from the server, we are going to implement a Timer class from the System.Threading namespace. Let’s create a new folder TimerFeatures and inside it a new class TimerManager:

We are using an Action delegate to execute passed callback function every two seconds. The timer will make a one-second pause before first execution. Finally, we just create a sixty seconds time slot for execution, to avoid limitless timer loop. If you want to learn more about delegates and how to use them to write better C# code, you can visit Delegates in C# article.

It is important to have a method which has one object parameter and returns a void result. The Timer class expects that kind of method in its constructor.

After the TimeManager implementation, let’s create a new folder DataStorage and inside it a new class DataManager. We are going to use this class to fake our data:

Finally, to complete this section, we are going to create a new controller file ChartController inside the Controllers folder:

In this controller class, we are using the IHubContext interface to create its instance via dependency injection. By using that instance object, we are able to access and call the hub methods. This is the reason why we don’t have any method in our ChartHub class. We don’t need any yet, because we are providing just one-way communication (server is sending data to the client only), and we can access all the hub methods with IHubContext interface.

Furthermore, in the Get action, we are instantiating the TimerManager class and providing a callback function as a parameter. This callback function will be executed every two seconds.

Now, we have to pay attention to the _hub.Clients.All.SendAsync("transferchartdata", DataManager.GetData()) expression. With it, we are sending generated data to all subscribed clients on the transferchartdata event. This means that every client if it has a listener on the transferchartdata event, will receive a data generated by the DataManager class. And that is exactly what we are going to do in the next section.

Angular Chart and SignalR Listener

We have currently finished our work on the server side, so let’s switch to the client side.

To use charts in Angular, we are going to install two required libraries:

Installing ng2Charts - SignalR with .NET Core and Angular

Installing Chartjs

As soon as we install required libraries, we are going to modify the angular.json file:

And finally, let’s modify the app.module.ts file:

Of course, the HttpClientModule is not required for the charts to work, but we are going to send the HTTP request towards our server, so we need it.

To continue, we are going to create a service file for the sole purpose to wrap the SignalR logic:

Additionally, we are going to create an interface ChartModel:

Having done that, let’s modify our service file:

First of all, we create the data array which will hold the data fetched from the server and will provide a data source for the chart. In the startConnection function, we build and start our connection as well as logging the message in the console. Finally, we have the addTransferChartDataListener function in which we subscribe to the event transferchardata and accept the data from the server with the data parameter. If we take a look at the Get action in the ChartController file, we are going to see that we broadcast the data on the same transferchartdata event: (_hub.Clients.All.SendAsync("transferchartdata", DataManager.GetData())).

And yes, those must match.

All we have left to do, for now, is to modify the app.component.ts file:

This logic is straightforward. We just start the connection, add our listener, and send request towards the Get action on our server.

This should be our current result:

 

SingalR connected - SignalR with .NET Core and Angular

Excellent. We can see that our data is received in a real-time and logged in the console window.

Of course, this is just part of our goal, so let’s get to the finish line.

To do that, let’s modify the app.component.html file:

And the app.component.ts file:

Now, our result should look like this:

SignalR chart completed - SignalR with .NET Core and Angular

This looks great. Our application is working as intended.

Sending Data via SignalR from the Client to the Server and Back

Until now, we’ve broadcasted data only from the server to the client (one-way communication). But what if we want to send some data from the client to the server and then to broadcast it to all the subscribed clients (all of that via SignalR)? Well, we can do that as well.

So let’s imagine that we want to send the current data to some API as soon as we click on our chart, and then to display them on any other client. To cover that example, we could create another Angular app, but for the sake of simplicity, we are going to implement all of that in our current app.

So, the first thing we want to do is to modify the ChartHub class in .NET Core:

Because we are starting the SignalR communication from the client, we need a hub endpoint to Invoke our data to. This BroadcastChartData method will receive the message from the client and then broadcast that same message to all the clients that listen on the bradcastchratdata event.

The second step is to modify the service file in Angular:

The first function will send data to our Hub endpoint and the second function will listen on the braodcastchartdata event.

The third step is to modify the app.component.ts file:

And finally, let’s provide the chartClicked event for our chart:

After all of the changes, we can inspect result:

SignalR - chart - two way communication

Excellent work. Everything works like a charm.

Of course, we can accomplish a lot more with SignalR and cover a whole load of features, but this is a good starting point for sure.

Conclusion

By reading this article, we could have learned:

  • How to install SignalR and prepare a basic configuration
  • The way to use Timer in .NET Core
  • How to provide a SignalR implementation on the client and server side
  • The way to use charts to consume real-time data sent via SignalR

If you have enjoyed reading this article and if you would like to receive the notifications about the freshly published .NET Core content we encourage you to subscribe to our blog.