Chat Application Using Angular 8, ASP.NET Core, Signal R

In this article, we are going to create a simple chat application using Angular 8, ASP.NET Core 2.2.0, and SignalR 1.1.0 as shown below.
 
Chat Application Using Angular 8, ASP.NET Core, Signal R
 
We need to install all the below-mentioned prerequisites on our development machine.
 
Prerequisite
  • .NET Core SDK 2.2.0 – download from here.
  • Node.js 10.15.3 – download from here.
  • Angular CLI 8.0 – Install Angular command package by executing this command: “npm install -g @angular/[email protected]

Set up ASP.NET Core with SignalR Project

 
Open the command prompt and enter the following command to create an ASP.NET Core web project as below.
 
Chat Application Using Angular 8, ASP.NET Core, Signal R
 
Install the following NuGet package in your project.
  • Microsoft.AspNetCore.SignalR
  • Microsoft.AspNetCore.SpaServices.Extensions
Chat Application Using Angular 8, ASP.NET Core, Signal R
 
Call SignalR in the “Startup.ConfigureServices” method to add SignalR services.
 
services.AddSignalR();
 

Create MessageHub Class

 
SignalR makes real-time client-to-server and server-to-client communications possible and it will call methods to connect clients from a server using SignalR Hub API. You can find more details about SignalR from here. Now, we need to perform the following steps to create the MessageHub class that is extending SignalR Hub API features.
  • Create Hubs Folder in the project
  • Declare MessageHub class that inherits from SignalR Hub
  • Add the NewMessage public method to get a new message from a connected client.
  • Then, Send an async message to all connected clients.
  1. using ChatApp.Models;  
  2. using Microsoft.AspNetCore.SignalR;  
  3. using System.Threading.Tasks;  
  4.   
  5. namespace ChatApp.Hubs  
  6. {  
  7.     public class MessageHub : Hub  
  8.     {  
  9.         public async Task NewMessage(Message msg)  
  10.         {  
  11.             await Clients.All.SendAsync("MessageReceived", msg);  
  12.         }  
  13.     }  
  14. }  
Then, add route to handle a request in Startup.ConfigureService method for MessageHub.
  1. app.UseSignalR(options =>  
  2. {  
  3.       options.MapHub<MessageHub>("/MessageHub");  
  4.  });   
Add a Message Class
  1. public class Message  
  2.    {  
  3.        public string clientuniqueid { getset; }  
  4.        public string type { getset; }  
  5.        public string message { getset; }  
  6.        public DateTime date { getset; }  
  7.    }  

Add Angular 8 into the project

 
We will scaffold Angular into our project. For this, we need to execute “ng new ClientApp --skip-install” on Visual Studio Code terminal. Here, --skip-install option is used to skip installation of the npm packages.
 
Chat Application Using Angular 8, ASP.NET Core, Signal R
 
Now, let us enter the “npm install” command to install all Angular npm packages in the terminal. And then, update the SPA static file service configuration to the Angular output files folder location. For this, we will add the below code to the “Startup.Configure” method.
  1. app.UseSpa(spa =>  
  2.             {  
  3.                 // To learn more about options for serving an Angular SPA from ASP.NET Core,  
  4.                 // see https://go.microsoft.com/fwlink/?linkid=864501  
  5.   
  6.                 spa.Options.SourcePath = "ClientApp";  
  7.   
  8.                 if (env.IsDevelopment())  
  9.                 {  
  10.                     //spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");  
  11.                     spa.UseAngularCliServer(npmScript: "start");  
  12.                 }  
  13.             });  
Here, UseAngularCliServer will pass the request through to an instance of Angular CLI server which keeps up-to-date CLI-built resources without having to run the Angular CLI server manually.
 
Now, add SignalR client library to connect MessageHub from the Angular as below screenshot.
 
Chat Application Using Angular 8, ASP.NET Core, Signal R
 

Create Chat Service to connect SignalR

 
Create chat.service.ts class to establish a connection with Message Hub and to publish & receive chat messages.
 
Then, we have added chat service as a provider in Ng Modules.
  1. import { EventEmitter, Injectable } from '@angular/core';  
  2. import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';  
  3. import { Message } from '../models/message';  
  4.   
  5. @Injectable()  
  6. export class ChatService {  
  7.   messageReceived = new EventEmitter<Message>();  
  8.   connectionEstablished = new EventEmitter<Boolean>();  
  9.   
  10.   private connectionIsEstablished = false;  
  11.   private _hubConnection: HubConnection;  
  12.   
  13.   constructor() {  
  14.     this.createConnection();  
  15.     this.registerOnServerEvents();  
  16.     this.startConnection();  
  17.   }  
  18.   
  19.   sendMessage(message: Message) {  
  20.     this._hubConnection.invoke('NewMessage', message);  
  21.   }  
  22.   
  23.   private createConnection() {  
  24.     this._hubConnection = new HubConnectionBuilder()  
  25.       .withUrl(window.location.href + 'MessageHub')  
  26.       .build();  
  27.   }  
  28.   
  29.   private startConnection(): void {  
  30.     this._hubConnection  
  31.       .start()  
  32.       .then(() => {  
  33.         this.connectionIsEstablished = true;  
  34.         console.log('Hub connection started');  
  35.         this.connectionEstablished.emit(true);  
  36.       })  
  37.       .catch(err => {  
  38.         console.log('Error while establishing connection, retrying...');  
  39.         setTimeout(function () { this.startConnection(); }, 5000);  
  40.       });  
  41.   }  
  42.   
  43.   private registerOnServerEvents(): void {  
  44.     this._hubConnection.on('MessageReceived', (data: any) => {  
  45.       this.messageReceived.emit(data);  
  46.     });  
  47.   }  
  48. }    

Create a Chat App Component

 
app.component.html:
  1. <div class="container">  
  2.   <h3 class=" text-center chat_header">Chat Application</h3>  
  3.   <div class="messaging">  
  4.     <div class="inbox_msg">  
  5.       <div class="mesgs">  
  6.         <div class="msg_history">  
  7.           <div *ngFor="let msg of messages">  
  8.           <div class="incoming_msg" *ngIf="msg.type == 'received'">  
  9.             <div class="incoming_msg_img"> </div>  
  10.             <div class="received_msg">  
  11.               <div class="received_withd_msg">  
  12.                 <p>  
  13.                  {{msg.message}}   
  14.                 </p>  
  15.                 <span class="time_date"> {{msg.date | date:'medium'}} </span>  
  16.               </div>  
  17.             </div>  
  18.           </div>  
  19.           <div class="outgoing_msg" *ngIf="msg.type == 'sent'">  
  20.             <div class="sent_msg">  
  21.               <p>  
  22.                   {{msg.message}}   
  23.               </p>  
  24.               <span class="time_date"> {{msg.date | date:'medium'}}</span>  
  25.             </div>  
  26.           </div>  
  27.         </div>  
  28.         </div>  
  29.         <div class="type_msg">  
  30.           <div class="input_msg_write">  
  31.             <input type="text" class="write_msg" [value]="txtMessage"  
  32.             (input)="txtMessage=$event.target.value" (keydown.enter)="sendMessage()" placeholder="Type a message" />  
  33.             <button class="msg_send_btn" type="button"  (click)="sendMessage()"><i class="fa fa-paper-plane-o" aria-hidden="true"></i></button>  
  34.           </div>  
  35.         </div>  
  36.       </div>  
  37.     </div>  
  38.   
  39.   </div>  
  40. </div>  
app.component.ts :
  1. import { Component, NgZone } from '@angular/core';  
  2. import { Message } from '../models/Message';  
  3. import { ChatService } from '../services/chat.service';  
  4.   
  5. @Component({  
  6.   selector: 'app-root',  
  7.   templateUrl: './app.component.html',  
  8.   styleUrls: ['./app.component.css']  
  9. })  
  10. export class AppComponent {  
  11.   
  12.   title = 'ClientApp';  
  13.   txtMessage: string = '';  
  14.   uniqueID: string = new Date().getTime().toString();  
  15.   messages = new Array<Message>();  
  16.   message = new Message();  
  17.   constructor(  
  18.     private chatService: ChatService,  
  19.     private _ngZone: NgZone  
  20.   ) {  
  21.     this.subscribeToEvents();  
  22.   }  
  23.   sendMessage(): void {  
  24.     if (this.txtMessage) {  
  25.       this.message = new Message();  
  26.       this.message.clientuniqueid = this.uniqueID;  
  27.       this.message.type = "sent";  
  28.       this.message.message = this.txtMessage;  
  29.       this.message.date = new Date();  
  30.       this.messages.push(this.message);  
  31.       this.chatService.sendMessage(this.message);  
  32.       this.txtMessage = '';  
  33.     }  
  34.   }  
  35.   private subscribeToEvents(): void {  
  36.   
  37.     this.chatService.messageReceived.subscribe((message: Message) => {  
  38.       this._ngZone.run(() => {  
  39.         if (message.clientuniqueid !== this.uniqueID) {  
  40.           message.type = "received";  
  41.           this.messages.push(message);  
  42.         }  
  43.       });  
  44.     });  
  45.   }  
  46. }  
Now, our chat application is ready. Let's run the following command in terminal and test apps.
  1. dotnet run  

Summary

 
In this article, we have learned how we can create a sample chat app using Angular 8 and ASP.NET Core with SignalR. Please find the entire source code here as an attachment and also on GitHub.