In modern web development, real-time data applications are becoming increasingly important. Whether you’re building live chat applications, collaborative tools, or financial dashboards, the ability to handle real-time data is essential. The MEAN stack, comprising MongoDB, Express.js, Angular, and Node.js, is a powerful choice for developing full-stack applications. In this blog post, we’ll explore how to build a real-time data application using Angular and Node.js.
Before we dive into real-time data handling, let’s briefly review the MEAN stack:
Real-time data refers to information that is delivered instantly after collection. In a typical web application, data is fetched from the server and displayed to the user, but real-time data involves continuous updates where changes are pushed from the server to the client automatically.
Real-time data is often necessary for applications such as:
Now, let’s break down how to implement real-time data handling with Angular and Node.js using WebSockets.
To get started, we’ll create a basic MEAN stack application with Angular as the front end, Node.js as the backend, and WebSockets to handle real-time communication.
First, you need to initialize a Node.js project and install necessary dependencies.
Initialize the Node.js project:
bash
code
mkdir mean-realtime-app
cd mean-realtime-app
npm init -y
Install dependencies:
You’ll need express
, socket.io
, and cors
for setting up the server and real-time communication.
bash
code
npm install express socket.io cors
Create the server:
In your project root, create a file called server.js
:
javascript
code
const express =
require(
‘express’);
const http =
require(
‘http’);
const socketIo =
require(
‘socket.io’);
const cors =
require(
‘cors’);
const app =
express();
const server = http.
createServer(app);
const io =
socketIo(server);
app.
use(
cors());
app.
get(
‘/’,
(req, res) => {
res.
send(
‘Real-Time Data with Angular and Node.js’);
});
// Handle WebSocket connections
io.
on(
‘connection’,
(socket) => {
console.
log(
‘New client connected’);
// Emitting data to the client
setInterval(
() => {
socket.
emit(
‘data’, {
time:
new
Date().
toISOString() });
},
1000);
socket.
on(
‘disconnect’,
() => {
console.
log(
‘Client disconnected’);
});
});
const
PORT = process.
env.
PORT ||
3000;
server.
listen(
PORT,
() => {
console.
log(
`Server is running on port ${PORT}`);
});
In this code:
socket.io
to manage WebSocket connections.socket.emit
.Next, let’s create the Angular app that will display real-time data received from the server.
Create an Angular application:
In the root of the project, create the Angular frontend using the Angular CLI:
bash
code
ng new frontend --routing=
true --style=scss
cd frontend
Install socket.io-client:
In the Angular project, install the socket.io-client
library to connect to the WebSocket server.
bash
code
npm install socket.io-client
Create a WebSocket service:
Inside the src/app
directory, create a new service called websocket.service.ts
:
typescript
code
import {
Injectable }
from
‘@angular/core’;
import { io,
Socket }
from
‘socket.io-client’;
@Injectable({
providedIn:
‘root’,
})
export
class
WebsocketService {
private
socket:
Socket;
constructor() {
this.
socket =
io(
‘http://localhost:3000’);
}
// Listen for ‘data’ event from the server
listenForRealTimeData() {
return
new
Observable(
(observer) => {
this.
socket.
on(
‘data’,
(data: any) => {
observer.
next(data);
});
});
}
}
Display real-time data in a component:
Now, create a component that will display the real-time data.
Generate a component called real-time
:
bash
code
ng generate component real-time
In real-time.component.ts
, inject the WebSocket service and display the data:
typescript
code
import {
Component,
OnInit }
from
‘@angular/core’;
import {
WebsocketService }
from
‘./websocket.service’;
@Component({
selector:
‘app-real-time’,
templateUrl:
‘./real-time.component.html’,
styleUrls: [
‘./real-time.component.scss’]
})
export
class
RealTimeComponent
implements
OnInit {
realTimeData:
string =
”;
constructor(
private websocketService: WebsocketService) {}
ngOnInit() {
this.
websocketService.
listenForRealTimeData().
subscribe(
(data: any) => {
this.
realTimeData = data.
time;
});
}
}
In real-time.component.html
, display the real-time data:
html
code
<div class=”container”>
<h1>Real-Time Data
</h1>
<p>{{ realTimeData }}
</p></div>
Update the app.component.html
:
Finally, include the RealTimeComponent
in your main app.component.html
:
html
code
<app-real-time></app-real-time>
Run the Node.js server:
In the project root, start the Node.js server:
bash
code
node server.js
Run the Angular app:
In the frontend
directory, run the Angular app:
bash
code
ng serve
Now, if you visit http://localhost:4200
, you should see the current time being displayed and updated every second.
socket.io
to handle WebSocket connections. It sends real-time data (the current timestamp) to connected clients every second.socket.io-client
. When new data is received, the component updates the view in real-time.WebSockets provide full-duplex communication channels over a single, long-lived connection. They are ideal for applications that require real-time data exchange between the client and server, such as:
In this tutorial, we’ve explored how to implement real-time data using Angular and Node.js with the MEAN stack. By using WebSockets, we can push real-time updates from the server to the client without requiring the client to poll for updates. This approach is efficient and well-suited for applications that require immediate data delivery.
With this setup, you can now build applications that feature live data updates, improving the user experience and providing real-time insights into your data.
Comments are closed