Real-Time Data Updates with .NET Core and Angular using SignalR
Introduction
Modern web applications require real-time updates — whether it’s live dashboards, trading platforms, chat apps, or notifications.
Traditionally, HTTP polling was used to check for changes, but it’s inefficient and slow.
In this article, you’ll learn how to implement a real-time data update system using .NET Core (SignalR) and Angular, giving users a smooth, responsive experience.
What is SignalR?
SignalR is a real-time communication library for ASP.NET Core that enables bi-directional communication between server and client.
Key features:
- Real-time communication (instant updates)
- Automatic connection management
- Fallback to older protocols if WebSockets are unavailable
- Strongly-typed hubs with .NET Core
Architecture Overview
Client (Angular)
⬇️ ⬆️
SignalR Hub (.NET Core)
⬇
Database / API / External Data Source
- The server listens for data updates.
- When data changes, the server broadcasts messages to all connected clients.
- The Angular client receives updates in real-time and updates the UI.
⚙️ Step 1: Create the .NET Core Backend
1.1 Create a new Web API project
dotnet new webapi -n RealtimeDemo
cd RealtimeDemo
1.2 Install SignalR
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 Program.cs
using RealtimeDemo.Hubs;
using RealtimeDemo.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSignalR();
builder.Services.AddHostedService<PriceSimulator>();
var app = builder.Build();
app.MapControllers();
app.MapHub<PriceHub>("/priceHub");
app.Run();
Step 2: Simulate Real-Time Data
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;
}
}
}
Step 3: Setup 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 backend and frontend:
dotnet run # Backend
ng serve # Frontend
Open the Angular app in your browser — prices update every 2 seconds in real-time.
Summary
Using SignalR with .NET Core and Angular, you can easily build real-time applications like:
- Live trading dashboards
- Collaborative apps (whiteboards, docs)
- Notification systems
- IoT monitoring dashboards
SignalR abstracts the complexity of real-time communication while Angular efficiently handles UI updates.
#dotnet #angular #signalr #realtime #webdev #csharp #frontend #backend
download sample code from github
I’m Morteza Jangjoo and “Explaining things I wish someone had explained to me”
Top comments (0)