shape
shape

Real-Time Data with Angular and Node.js in the MEAN Stack: A Detailed Guide

  • Home
  • MEAN
  • Real-Time Data with Angular and Node.js in the MEAN Stack: A Detailed Guide

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.

What is the MEAN Stack?

Before we dive into real-time data handling, let’s briefly review the MEAN stack:

  • MongoDB: A NoSQL database used to store application data.
  • Express.js: A minimal and flexible Node.js web application framework that provides a robust set of features.
  • Angular: A front-end web application framework for building dynamic single-page applications (SPAs).
  • Node.js: A server-side JavaScript runtime that allows you to run JavaScript on the server.
Why Real-Time Data?

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:

  • Chat applications
  • Stock market trackers
  • Social media feeds
  • Real-time collaborative tools

Now, let’s break down how to implement real-time data handling with Angular and Node.js using WebSockets.

Setting Up the Project

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.

Step 1: Initialize Node.js Backend with WebSocket Support

First, you need to initialize a Node.js project and install necessary dependencies.

Initialize the Node.js project:

bash

 code

mkdir mean-realtime-appcd 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:

  • We’re using socket.io to manage WebSocket connections.
  • Every second, the server sends the current time to connected clients using socket.emit.
Step 2: Set Up Angular Frontend to Listen for Real-Time Data

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=scsscd 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>

    Step 3: Run the Application

    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.

    How Does This Work?
    • WebSocket Server: The Node.js server uses socket.io to handle WebSocket connections. It sends real-time data (the current timestamp) to connected clients every second.
    • Angular Client: The Angular app listens for updates from the WebSocket server using the socket.io-client. When new data is received, the component updates the view in real-time.
    Why Use WebSockets for Real-Time Data?

    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:

    • Chat applications
    • Gaming applications
    • Live tracking and updates
    • Collaborative document editing
    Conclusion

    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.

    Additional learning resources:
    • C LANGUAGE COMPLETE COURSE – IN HINDI – Link
    • CYBER SECURITY TUTORIAL SERIES – Link
    • CODING FACTS SERIES – Link
    • SKILL DEVELOPMENT SERIES – Link
    • PYTHON PROGRAMMING QUIZ – Link
    • CODING INTERVIEW QUIZ – Link
    • JAVA PROGRAMMING QUIZ – Link
    • C PROGRAMMING QUIZ – Link

    Comments are closed

    0
      0
      Your Cart
      Your cart is emptyReturn to shop