Implement Real-Time Communication Using SignalR with Angular

Step-by-step SignalR tutorials with Angular

Dec 5, 2024·

4 min read

By default, a webpage works in request and response mode. The client sends a request to the server and receives the response.

What if the data changed dynamically in the server, let’s say by some other user and the client application should show the same to other users in real-time? Ex. Chat apps

Traditionally, we used a method called polling, where clients continuously send requests to the server to check for any changes and receive updated content. This approach has drawbacks because the server receives frequent requests even when there are no changes, and clients make unnecessary calls to the server.

Here comes the solution, SignalR by Microsoft.

What is SignalR?

SignalR is an open-source, real-time messaging framework for ASP.NET developed by Microsoft. It enables developers to create interactive and dynamic apps that instantly push data between servers and connected clients.

In this blog post, we are going to use asp.net core API to create a SignalR server and angular client app to receive the messages.

SignalR server API project

Open any folder in the terminal and run the below command to create a new ASP.NET Core API project.

dotnet new webapi -n SignalrServer

Navigate to the newly created folder in the terminal and run the following command to add the SignalR package.

dotnet add package Microsoft.AspNetCore.SignalR.Client

Open the project with your preferred IDE and make the following changes.

Adding SignalR and creating SignalR Hub:

Add the below MessageHub and it should be derived from Hub which is a base class for the SignalR hub.

A Hub is a high-level pipeline that enables direct communication between the client and server, allowing them to call each other's methods. Essentially, a Hub serves as the communication foundation between the client and server when using SignalR.

public class MessageHub: Hub
{
}

In program.cs file, add the below.

builder.Services.AddSignalR()
...
app.MapHub<MessageHub>("latest-messages");
...
app.MapGet("/send-messages", (IHubContext<MessageHub> notificationsHub) => notificationsHub.Clients.All.SendAsync("Receive-Messages",$"Message from server - {DateTime.Now}!"));

builder.Services.AddSignalR() → Adds the SignalR to the Service collection

app.MapHub<MessageHub>("latest-messages") → Add SignalR to the pipeline with the given path.

app.MapGet("/send-messages") → Add this line to send messages to connected SingalR clients. Receive-Messages is a hub method where clients listen for messages.

SignalR Client - Angular WebApp

Similar to the API project, open the terminal again to create a new Angular project.

Run the below command to create an angular project.

ng new SingnalrClient

Navigate to the newly created project folder SingnalrClient and run the following command to install the SingnalR package.

npm i @microsoft/signalr

Add the below code to the app.component.ts in OnInit method.

import * as signalR from '@microsoft/signalr'; //1

export class AppComponent implements OnInit {
  serverMessages: string[] = [];
  ngOnInit(): void {
    let connection = new signalR.HubConnectionBuilder()
      .withUrl("http://localhost:5213/latest-messages")
      .build();

    connection.on("Receive-Messages", data => {
      this.serverMessages.push(data);
      console.log(data);
    });

     connection
     .start()
     .then(() => console.log('Connection started'))
     .catch(err => console.log('Error while starting connection: ' + err))
    //   .then(() => connection.invoke("send", "Hello"));

  }
  title = 'SingnalrClient';
}

HubConnectionBuilder().withUrl uses the SingalR hub path and creates new connection.

connection.on listens to the hub method Receive-Messages and shows the message to the users.

connection.start() starts the connection with the SignalR server.

Demo

Run the API project with dotnet run command in the terminal or with IDE. Run the Angular project with ng serve the command. Now, open the browser with the below URLs.

Angular (view messages) → http://localhost:4200/

API (send messages) → http://localhost:5213/send-messages

Now, if you refresh the API URL, the angular app displays the messages from the server.

That’s it. Now if any changes in the server, it will be available in the client. You can extend this example for your use cases.

Conclusion:

This article explains how to use SignalR, a real-time messaging tool for ASP.NET, with Angular to create dynamic apps. It describes how to set up an ASP.NET Core API with SignalR, set up CORS, create an Angular project, and connect Angular to the SignalR hub for real-time communication. The article also talks about adding real-time features, fixing common problems, and possible uses for SignalR and Angular in apps that need frequent updates or notifications.

References:

Introduction to SignalR | Microsoft Learn

How to Use SignalR with .NET Core and Angular - Real-Time Charts

Adding Real-Time Functionality To .NET Applications With SignalR