ASP.NET Core SignalR

ASP.NET Core SignalR

Client to Server Communication with Angular.

·

3 min read

Table of contents

No heading

No headings in the article.

Welcome to part 2 of this series. In the previous section, we managed to create a simple chat app with AspNetCore with Razor pages. For now, we will connect SignalR, Angular and AspNetCore.

Before we proceed, in the previous series, we need to add cors in the program.cs file.

using SignalRChat.Hubs;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddSignalR();
//Add cors
builder.Services.AddCors();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();
app.MapHub<ChatHub>("/chathub");

app.Run();

Prerequisites:

Check on the previous section on this link.

https://jeffnyak.hashnode.dev/aspnet-core-signalr

To be able to use Angular, you need to make sure you have nodejs installed on your machine. Find the link below for your preferred Operating System. https://nodejs.org/en/download/current/

Once nodejs is installed, you can confirm by typing the following command in your terminal

$ node --version
v16.14.0

I currently have version 16 installed.

Let's install angular cli globally.

npm install -g @angular/cli

Confirm version.

 ng --version

Create a new project and name it as signalRClient.

ng new signalRClient --routing

Angular comes with an inbuilt routing module.

Once the project has been created try and run via the following command.

ng serve

This opens the app on the browser with a default localhost: 4200

You can also try npm start.

npm start

We will create a chat component and a signalR service. Angular does this via the terminal.

ng g c components/chat
ng g s services/signalR

Go to app.component.html file, remove the default code then replace it with app chat component.

<app-chat></app-chat>

The above command generates a component and a service and saves them in their respective folders.

Let's install the Microsoft SignalR client for angular. here is the npm package link

https://www.npmjs.com/package/@microsoft/signalr

npm install @microsoft/signalr
# or
yarn add @microsoft/signalr

In the services folder, open signal-r.service.ts and paste the below code.

import { Injectable } from '@angular/core';

import * as signalR from '@microsoft/signalr';
import { HubConnectionBuilder } from '@microsoft/signalr';

@Injectable({
  providedIn: 'root'
})
export class SignalRService {
  connection:any;
  connectionURL:string ='http://localhost:5145/chathub';
  constructor() { }

  startConnection = () =>{
    this.connection = new HubConnectionBuilder().withUrl(`${this.connectionURL}`, {
                        skipNegotiation: true,
                        transport: signalR.HttpTransportType.WebSockets
                      })
                      .build();
    this.connection.start()
                    .then(() =>{
                      console.log("Connected successfully")
                    }).catch((error:any) =>{
                      console.log(error);
                    })
  }
}

From the above code snippets, we are importing SignalR and HubConnectionBuilder from Microsoft signalr

import * as signalR from '@microsoft/signalr';
import { HubConnectionBuilder } from '@microsoft/signalr'

We have also the connection URL from the server.

connectionURL:string ='http://localhost:5145/chathub';

We have created a method for starting signal r connection. we will call the method via dependency injection in the chat component.ts file.

startConnection = () =>{
    this.connection = new HubConnectionBuilder().withUrl(`${this.connectionURL}`, {
                        skipNegotiation: true,
                        transport: signalR.HttpTransportType.WebSockets
                      })
                      .build();
    this.connection.start()
                    .then(() =>{
                      console.log("Connected successfully")
                    }).catch((error:any) =>{
                      console.log(error);
                    })
  }

Open chat.component.ts file and paste the following code.

import { Component, OnInit } from '@angular/core';

import { SignalRService } from '../../services/signal-r.service';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.css']
})

export class ChatComponent implements OnInit {
  constructor(public signalRService: SignalRService) { }

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

}

Here we are passing on the signal r service via dependency injection in the constructor. It is public so that it can be accessed anywhere.

constructor(public signalRService: SignalRService) { }

Then we call on the startConnection method using angular life cycle hook ngOninit.

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

Now run both Angular and AspNetCore projects.

Go to the angular project and check on the console log on the browser. You will be able to see the successful connection.

See you at the next one.