Integrate SignalR with Angular

Aditya Pradhan
4 min readOct 6, 2024

--

Banner

In the ever-evolving world of frontend development, real-time interactive is becoming a necessity. Whether you’re building a chat application, notifications system, or live data dashboard, SignalR is one of the most efficient libraries to facilitate real-time communication. As an Angular developer, integrating SignalR into your application provides an easy and reliable way to enable this real-time feature without dealing with low-level complexities like WebSockets or polling.

In this article, we will walk through the steps to integrate SignalR with Angular.

Note: SignalR requires a .NET backend to function correctly, as it is part of the ASP.NET Core framework. This setup allows for a powerful combination of .NET on the server and Angular on the frontend for building real-time web applications.

What is SignalR?

SignalR simplifies adding real-time web functionality to applications. It automatically chooses the best real-time communication mechanism (WebSockets, Server-Sent Events, or long polling) depending on the client’s environment. The beauty of SignalR lies in its simplicity and efficiency in enabling real-time data transmission, such as notifications, chats or live feeds.

Why use SignalR with Angular?

Angular is one of the most powerful frontend frameworks for building a dynamic, client-side applications. By integrating SignalR, you enable Angular apps to communicate in real-time with the backend, opening up possibilities for chat applications, notifications, live data updates, and more.

Key Benefits for Angular Developers:

  • Real-time Interactions: Automatically update the UI when new data arrives without the need for polling.
  • Transport Layer Abstraction: Automatically chooses the best transport protocol (WebSockets, Server-Sent Events, or Long Polling) based on the client’s environment.
  • Better User Experience: Improved responsiveness and interaction as users receive instant updates.

Installing SignalR in an Angular Project

To get started with SignalR in Angular, you first need to install the SignalR client library.

Step 1: Install the SignalR client

Run the following command to install the SignalR client library:

npm install @microsoft/signalr

This will install the SignalR JavaScript client, allowing Angular to communicate with the SignalR backend.

Creating the SignalR Service in Angular

In Angular, services are used to organize and handle business logic. We’ll create a SignalR service that will manage the connection between the Angular app and the server.

Step 2: Create the SignalR Service

Create a new service in your Angular project named signalr.service.ts. This service will be responsible for:

  • Establishing the connection with the SignalR server.
  • Handling incoming messages.
  • Sending messages to the server.
import { Injectable } from '@angular/core';
import * as signalR from '@microsoft/signalr';

@Injectable({
providedIn: 'root'
})
export class SignalRService {
private hubConnection: signalR.HubConnection;

constructor() {}

public startConnection = () => {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('https://yourserverurl/chathub') // URL of the SignalR hub
.build();

this.hubConnection
.start()
.then(() => console.log('SignalR Connection started'))
.catch(err => console.log('Error establishing SignalR connection: ' + err));
}

public addMessageListener = () => {
this.hubConnection.on('ReceiveMessage', (user: string, message: string) => {
console.log(`User: ${user}, Message: ${message}`);
});
}

public sendMessage = (user: string, message: string) => {
this.hubConnection.invoke('SendMessage', user, message)
.catch(err => console.error(err));
}
}

Breakdown:

  • startConnection(): Initializes the connection between the Angular app and the SignalR hub.
  • addMessageListener(): Listens for messages broadcasted from the server and logs them.
  • sendMessage(): Sends a message from the Angular app to the server.

Sending and Receiving Real-Time Data

Now that we have the SignalR service in place, we can integrate it into Angular components. For example, if you’re building a chat application, you’ll want to send and receive messages in real-time.

Step 3: User SignalR in Angular Components

Inject the SignalRService into your component, and use it to start the connection, listen for messages, and send data.

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

@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
})
export class ChatComponent implements OnInit {
user: string = '';
message: string = '';

constructor(public signalRService: SignalRService) {}

ngOnInit() {
this.signalRService.startConnection();
this.signalRService.addMessageListener();
}

sendMessage() {
this.signalRService.sendMessage(this.user, this.message);
this.message = ''; // Clear the input after sending
}
}

Breakdown:

  • ngOnInit(): Starts the SignalR connection and sets up the message listener as soon as the component is initialized.
  • sendMessage(): Uses the SignalRService to send messages to the server when the user submits a message.

This simple structure allows your Angular component to communicate in real-time with the server, instantly sending and receiving messages.

Handling Reconnections

In real-world scenarios, connections can drop or experience interruptions. SignalR provides automatic reconnection, but you can also handle reconnection logic manually in your Angular service to improve user experience.

Step 4: Add Reconnection Logic

To handle reconnections, add the following code to the SignalRService:

public handleDisconnects = () => {
this.hubConnection.onclose(() => {
console.log('Connection lost. Attempting to reconnect...');
setTimeout(() => this.startConnection(), 3000); // Try reconnecting after 3 seconds
});
}

By calling handleDisconnects() during initialization, you ensure that the app attempts to reconnect after the connection is dropped, improving overall stability and reliability.

Conclusion

By integrating SignalR into your Angular application, you can easily implement real-time communication with minimal setup and code complexity. SignalR’s ability to handle multiple transport mechanisms and its ease of use with Angular make it an excellent choice for real-time web applications like chats, notifications, live dashboards, and more.

Key Takeaways:

  • SignalR provides a simple yet powerful API for real-time data exchange.
  • Angular services are ideal for managing the SignalR connection and handling messages.
  • SignalR’s built-in reconnection features ensure reliability in production environments.

With this setup, you can build interactive, real-time Angular applications that provide a smooth and engaging user experience. 🚀

--

--

Aditya Pradhan
Aditya Pradhan

Written by Aditya Pradhan

Experienced Software Developer specializing in delivering high-performance solutions with Angular

No responses yet