You may have come across the requirement to push data in real time to an Angular Grid. To push data to the browser, you need a technology called WebSocket. You can implement that using NodeJS or ASP.NET SignalR. For the purpose of this article, we will use Web Sockets with NodeJS.
In the first half of this article, we will create an API which will use Web Sockets to push data to the client, and, in second half of the article, we will create an Angular application to consume that. In the Angular application, we will use Ignite UI for Angular Grid. However, you can also use a simple HTML table to consume data in real time from web socket. In this article, we will learn to consume data in real time from NodeJS Web Socket in a HTML table as well as Ignite UI Angular Data Grid. We will witness difference in performance in these two approaches.
You can learn more about Ignite UI for Angular: here
Let us start with creating NodeJS API. Create a blank folder and add a file called package.json. In package.json, add dependencies of
More or less your package.json file should look like below:
You can pull data from any type of database such as relational data base, No SQL database, etc. However, for purpose of this post, I am going to keep it simple and have hardcoded data in the data.js file. This file will export a JSON array, which we will push using web socket and timer.
Add a file in folder called data.js and add the following code in it.
You can find data with 1200 rows here.
From data.js file, we are returning TradeBlotter data. Now in your project folder, you should have two files: package.json and data.js
At this point in time, run the command, npm install, to install all dependencies mentioned in package.json file. After running command, you will have the node_modules folder in your project folder. Also, add server.js file in the project. After all these steps, your project structure should have following files and folders.
- data dot js
- server dot js
- Node_modules folder
In server.js, we will start with first importing required modules,
Once required modules are imported, add route-using express as below:
app.use(express.static(__dirname + ‘/dist’));
On connecting the socket, we are performing following tasks:
- Fetching data
- Starting timer(We will talk about this function later in the post)
- On disconnect event deleting the socket
We are calling a function updateData() which will update data. In this function, we are looping through local data and updating two properties, Coupon and Notional, with random number between ranges.