Skip to main content

Command Palette

Search for a command to run...

Real-Time Data Updates with .NET Core and Angular using SignalR

Published
4 min read
Real-Time Data Updates with .NET Core and Angular using SignalR
M

Morteza Jangjoo, Senior .NET Backend Developer with 15+ years of experience in C#, ASP.NET Core, SQL Server, and Microservices. Skilled in building scalable, high-performance systems.


Introduction

Modern web applications require real-time updates — whether it’s live dashboards, chat systems, trading platforms, or notifications.
Traditionally, you’d rely on HTTP polling to check for changes, but that approach is inefficient and slow.

In this article, you’ll learn how to build a real-time data update system using .NET Core (SignalR) and Angular — a powerful combination for creating responsive and dynamic applications.

What is SignalR?

SignalR is a real-time communication library for ASP.NET Core that enables bi-directional communication between the server and client.
It abstracts away the complexity of WebSockets and gracefully falls back to other protocols when WebSockets are not supported.

Key features:

  • Real-time communication (instant updates)

  • Connection management

  • Automatic fallback (WebSockets → Server-Sent Events → Long Polling)

  • Strongly-typed hubs with .NET 6+


Architecture Overview

Here’s the basic architecture:

Client (Angular)
   ⬇️ ⬆️
SignalR Hub (.NET Core)
   ⬇️
Database / API / External Data Source
  1. The server (SignalR Hub) listens for new or updated data.

  2. When data changes, the server broadcasts messages to all connected clients.

  3. The Angular app receives the updates in real-time and updates the UI instantly.


Step 1: Create the .NET Core Backend

1.1 Create a new project

dotnet new webapi -n RealtimeDemo
cd RealtimeDemo

1.2 Add SignalR package

dotnet add package Microsoft.AspNetCore.SignalR

1.3 Create a SignalR Hub

Hubs/PriceHub.cs

using Microsoft.AspNetCore.SignalR;

namespace RealtimeDemo.Hubs
{
    public class PriceHub : Hub
    {
        public async Task SendPriceUpdate(string symbol, decimal price)
        {
            await Clients.All.SendAsync("ReceivePriceUpdate", symbol, price);
        }
    }
}

1.4 Register SignalR in the backend

Program.cs

using RealtimeDemo.Hubs;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();
builder.Services.AddControllers();

var app = builder.Build();
app.MapControllers();
app.MapHub<PriceHub>("/priceHub");
app.Run();

Step 2: Simulate Real-Time Data

To simulate live updates (e.g., stock prices):

Services/PriceSimulator.cs

using Microsoft.AspNetCore.SignalR;
using RealtimeDemo.Hubs;
using System.Timers;

namespace RealtimeDemo.Services
{
    public class PriceSimulator : IHostedService
    {
        private readonly IHubContext<PriceHub> _hubContext;
        private System.Timers.Timer _timer = new(2000);
        private readonly Random _random = new();

        public PriceSimulator(IHubContext<PriceHub> hubContext)
        {
            _hubContext = hubContext;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _timer.Elapsed += async (sender, args) =>
            {
                var price = Math.Round((decimal)(_random.NextDouble() * 100), 2);
                await _hubContext.Clients.All.SendAsync("ReceivePriceUpdate", "EUR/USD", price);
            };
            _timer.Start();
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _timer.Stop();
            return Task.CompletedTask;
        }
    }
}

Register it in Program.cs:

builder.Services.AddHostedService<PriceSimulator>();

Step 3: Setup the Angular Frontend

3.1 Install SignalR client

npm install @microsoft/signalr

3.2 Create a SignalR Service

src/app/services/signalr.service.ts

import { Injectable } from '@angular/core';
import * as signalR from '@microsoft/signalr';

@Injectable({ providedIn: 'root' })
export class SignalRService {
  private hubConnection!: signalR.HubConnection;
  public latestPrice: number = 0;

  startConnection(): void {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl('https://localhost:5001/priceHub')
      .build();

    this.hubConnection
      .start()
      .then(() => console.log('SignalR connection started'))
      .catch(err => console.error('Error connecting to SignalR', err));

    this.hubConnection.on('ReceivePriceUpdate', (symbol, price) => {
      this.latestPrice = price;
      console.log(`${symbol} => ${price}`);
    });
  }
}

3.3 Display Real-Time Data in Component

src/app/app.component.ts

import { Component, OnInit } from '@angular/core';
import { SignalRService } from './services/signalr.service';

@Component({
  selector: 'app-root',
  template: `
    <div class="container">
      <h1>💹 Real-Time Price Updates</h1>
      <h2>EUR/USD: {{ signalRService.latestPrice | number:'1.2-2' }}</h2>
    </div>
  `,
  styles: [`
    .container { text-align: center; padding: 50px; font-family: Arial; }
  `]
})
export class AppComponent implements OnInit {
  constructor(public signalRService: SignalRService) {}

  ngOnInit(): void {
    this.signalRService.startConnection();
  }
}

Step 4: Run the Application

Start both servers:

dotnet run
ng serve

Now open your Angular app — you’ll see real-time price updates every 2 seconds coming directly from the backend.


Summary

By using SignalR in .NET Core and Angular, you can easily create real-time applications with instant updates, improving responsiveness and user experience.

You’ve learned:

  • What SignalR is and how it works

  • How to build a backend Hub in .NET Core

  • How to connect Angular with SignalR

  • How to push live updates from the server to the client


Next Steps

You can extend this setup to:

  • Real-time trading dashboards

  • Notification systems

  • Collaborative apps (whiteboards, documents)

  • IoT dashboards

download sample code from github


#dotnet #angular #signalr #websockets #realtime #programming #hashnode #csharp


I’m Morteza Jangjoo and “Explaining things I wish someone had explained to me”