SignalR Introduction And Implementation Using The .NET Core 6 Web API And Angular 14

Introduction

SignalR is a real-time communication library that allows you to add real-time functionality to your applications, enabling bi-directional communication between clients and servers. In this example, we’ll introduce SignalR and demonstrate its implementation using a .NET Core 6 Web API backend and an Angular 14 frontend.

Step 1: Create .NET Core 6 Web API Project

  1. Create a new .NET Core Web API project using .NET CLI or Visual Studio.

Step 2: Install SignalR NuGet Package

In the .NET Core Web API project, install the SignalR NuGet package:

dotnet add package Microsoft.AspNetCore.SignalR

Step 3: Implement SignalR Hub

Create a SignalR hub by adding a new class to your project:

using Microsoft.AspNetCore.SignalR;

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

Step 4: Configure SignalR in Startup.cs

In the Startup.cs file, configure SignalR services and routes:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
        // Add other services
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Configure other middleware

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<ChatHub>("/chatHub");
        });
    }
}

Step 5: Create Angular 14 Application

  1. Create a new Angular application using the Angular CLI:
ng new signalr-angular-app
  1. Navigate to the application directory:
cd signalr-angular-app

Step 6: Install SignalR Client Library

Install the SignalR client library in your Angular application:

npm install @microsoft/signalr

Step 7: Implement SignalR Service

Create a SignalR service in your Angular application to manage the communication with the SignalR hub:

import { Injectable } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@microsoft/signalr';

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

  constructor() {
    this.hubConnection = new HubConnectionBuilder()
      .withUrl('/chatHub')
      .build();
  }

  startConnection(): Promise<void> {
    return this.hubConnection.start();
  }

  sendMessage(user: string, message: string): void {
    this.hubConnection.invoke('SendMessage', user, message);
  }

  onReceiveMessage(callback: (user: string, message: string) => void): void {
    this.hubConnection.on('ReceiveMessage', callback);
  }
}

Step 8: Implement Angular Component

Implement an Angular component to use the SignalR service and interact with the SignalR hub:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  user: string;
  message: string;
  messages: string[] = [];

  constructor(private signalRService: SignalRService) {}

  ngOnInit(): void {
    this.signalRService.startConnection()
      .then(() => {
        this.signalRService.onReceiveMessage((user, message) => {
          this.messages.push(`${user}: ${message}`);
        });
      })
      .catch(error => console.error(error));
  }

  sendMessage(): void {
    if (this.user && this.message) {
      this.signalRService.sendMessage(this.user, this.message);
      this.message = '';
    }
  }
}

Step 9: Implement Angular Template

Update the Angular component’s template (app.component.html) to display the chat interface:

<div>
  <h1>SignalR Chat</h1>
  <div>
    <label>User: </label>
    <input [(ngModel)]="user" />
  </div>
  <div>
    <label>Message: </label>
    <input [(ngModel)]="message" />
    <button (click)="sendMessage()">Send</button>
  </div>
  <div>
    <ul>
      <li *ngFor="let msg of messages">{{ msg }}</li>
    </ul>
  </div>
</div>

Step 10: Run the Application

Run both the .NET Core Web API and the Angular application. Open the Angular application in a web browser and test the real-time chat functionality.

In summary, SignalR provides a powerful way to implement real-time communication in your applications. In this example, we demonstrated how to use SignalR to build a simple real-time chat application using a .NET Core 6 Web API backend and an Angular 14 frontend. You can extend and customize this example to meet your specific requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *