How To Do Live Data Refresh In Angular 11 Using SignalR

Introduction

In the previous article, we created an Angular 11 app to perform CRUD operations on Azure Cosmos DB using .NET 5 REST API. In this article, we will add SignalR to our front-end app so that we can get live data to refresh whenever there is an insert/update/delete in the database.

Prerequisites 

  • Azure account - If you don't have it already you can create one for free by visiting Cloud Computing Services | Microsoft Azure
  • Azure Cosmos DB Setup - Create a database in Azure Cosmos DB called VideogamesDB and a container called Videogames. If you want step-by-step instructions on how to do that please follow this article
  • .NET 5 REST API - Please follow this article to create .NET 5 REST API. We will be updating it so it can broadcast a signal whenever there is an update/insert/delete in Azure Cosmos DB 
  • Angular 11 App - We will be updating the angular app created in this article

.NET 5 API Changes

Step 1 - Edit Startup.cs Class 

Add  services.AddSignalR(); to  public void ConfigureServices(IServiceCollection services) method.

How to do live data refresh in Angular 11 using SignalR

Add endpoints.MapHub<VideogameHub>("/Videogame"); to  public void Configure(IApplicationBuilder app, IWebHostEnvironment env) method as shown in screenshot below

How to do live data refresh in Angular 11 using SignalR

Step 2 - Add VideogameHub.cs class

Add a new folder called HubConfig and inside that add a new class VideogameHub

How to do live data refresh in Angular 11 using SignalR

Copy-paste the following code in VideogameHub class

using Microsoft.AspNetCore.SignalR;
namespace AzureCosmosEFCoreCRUD.HubConfig {
    public class VideogameHub: Hub {}
}

VideogameHub is derived from base class Hub which acts as a communication link between client and server when using SignalR.

Step - Edit VideogameController.cs class

Add the following code into VideogameController class.

We have to create an instance of IHubContext via dependency injection. We will be using this instance to send data from server to client.

How to do live data refresh in Angular 11 using SignalR

We will be using this instance to send signal from server when a POST(AddVideogame) /PUT (UpdateVideogameByName) /DELETE (DeleteVideogameById) operation happens on Azure cosmos DB. Add the following code into the above mentioned methods - await _hub.Clients.All.SendAsync("transferdata", new List<Videogames>());

How to do live data refresh in Angular 11 using SignalR

How to do live data refresh in Angular 11 using SignalR

How to do live data refresh in Angular 11 using SignalR

Angular Changes

Step 1 - Install package 

Run the following command on VS Code terminal npm install @aspnet/signalr --save

Step 2 - Modify videogameservice.service.ts file

Add the following methods to the service,

startConnection - this is used to establish and start the connection with signalR. 

In ".withUrl('https://localhost:44371/Videogame')"  https://localhost:44371/ is the domain name and "Videogame" should match the value provided in.NET 5 API startup class here "endpoints.MapHub<VideogameHub>("/Videogame");"

public startConnection = () => {
    this.hubConnection = new signalR.HubConnectionBuilder().withUrl('https://localhost:44371/Videogame').build();
    this.hubConnection.start().then(() => console.log('Connection started')).catch(err => console.log('Error while starting connection: ' + err))
}

addDataListener - this will listen to changes transmitted by SignalR

"transferdata" should match the name of the method sent by the server (await _hub.Clients.All.SendAsync("transferdata", new List<Videogames>());)

public addDataListener = () => {
    this.hubConnection.on('transferdata', (data) => {
        this.updateDataTable();
    });
}

updateDataTable and onDataUpdate - This is used to call a method in videogamelist.component.ts which will be called to update the data table.

private updateDataTable!: () => void;
onDataUpdate(fn: () => void) {
    this.updateDataTable = fn;
}

Add the readonly variable private hubConnection!: signalR.HubConnection;

Step 3 - Modify videogamelist.component.ts file

Add the following code to ngOnInit function

this.service.startConnection();
this.service.addDataListener();
this.service.onDataUpdate(this.updateDataTable.bind(this));

Add the method to destroy and render the table again

updateDataTable() {
    var table = $("#videogameslist").DataTable();
    table.destroy();
    this.loadVideogameList();
}

Modify deletebuttonclicked method so that table can be recreated when a delete operation happens.

How to do live data refresh in Angular 11 using SignalR

Testing and Summary

Open the website on two browsers side-by-side. Open the home page on one browser and add a videogame on another browser. If everything goes well when the videogame is added on one browser the table on other browser will be updated automatically. Try the edit and delete endpoints to make sure they work correctly.

In this article, we learned how we can integrate real-time data update functionality in our app using just a few lines of code.