Chat Application using Angular 8, Asp.net Core 2.2.0, Signal R 1.1.0


In this article, we are going to create a simple chat application using Angular 8, Asp.net Core 2.2.0, Signal R 1.1.0 as shown below:

We install above all prerequisite following in our development machine:
Prerequisite
  • .Net Core SDK 2.2.0 – download from here.
  • Nodejs 10.15.3 – download from here.
  • Angular CLI 8.0 – Install angular command package by executing this command: “npm install -g @angular/cli@8.0.0
Setup Asp.net Core with Signal R Project:
open a command prompt and enter create asp.net core web project as below:

Install the following NuGet package in our project:
  • Microsoft.AspNetCore.SignalR
  • Microsoft.AspNetCore.SpaServices.Extensions
Call SignalR in the “Startup.ConfigureServices” method to add SignalR services:
  1. 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 detail about SignalR from here. Now we perform the following steps to create MessageHub class that is extending SignalR Hub API features:
  • Create Hubs Folder in the project
  • Declare MessageHub class that inherits from SignalR Hub
  • Add NewMessage public method to get a new message from a connected client.
  • Then, Send an async message to all connected client.
  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 scaffold Angular into our project, for this, we execute “ng new ClientApp --skip-install” on visual studio code terminal and Here, --skip-install option is used to skip installation of the npm packages.
Now we enter “npm install” command to install all angular npm packages in the terminal. And then, update SPA static file service configuration to angular output files folder location. for this, we add below code to “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:

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 following command in terminal and test apps:
  1. dotnet run  
Summary:
In this article, we have learned about how we can create sample chat app using angular 8, asp.net core with Signal R. Please find entire source code on GitHub.

Comments

Popular Posts

Contact Application Using ASP.NET Core Web API, Angular 6.0, And Visual Studio Code - Part One

Contact Application Using ASP.NET Core Web API, Angular 6.0, And Visual Studio Code - Part Two

Send Email With SharePoint Lookup Columns Data Using Power Automate

Contact application - Upgrade Asp.net Core 2.0 to 2.1

Create SSRS Drill Down Report

Get group permission list in which current user is member using JavaScript in SharePoint Online CSOM

Typescript Basics