Angular 7 WebSocket Example: A Comprehensive Guide

WebSocket is a protocol that enables two-way communication between a client and a server over a single, long-lived connection. This allows real-time data to be transmitted without the need for continuously polling the server for updates. In this article, we will explore how to implement WebSocket in an Angular 7 application.

What is Angular 7?

Angular 7 is the latest version of the Angular framework, which is developed and maintained by Google. It is a powerful tool for creating dynamic web applications with a clean and modular architecture. Angular 7 comes with a range of new features and improvements, including better performance, enhanced tooling, and improved support for web standards.

Setting up an Angular 7 Application

Before we can begin implementing WebSocket in our Angular 7 application, we need to set up a basic application. We can do this using the Angular CLI (Command Line Interface), which provides a range of useful tools and commands for creating and managing Angular projects.

  1. First, make sure you have Node.js and NPM (Node Package Manager) installed on your system.
  2. Open a terminal or command prompt and run the following command to install the Angular CLI globally:
    npm install -g @angular/cli
  3. Once the installation is complete, navigate to your desired project directory and run the following command to create a new Angular 7 application:
    ng new my-app
  4. This will create a new Angular 7 project with the name ‘my-app’ in your current directory.
  5. Navigate to the project directory using the following command:
    cd my-app
  6. Finally, run the following command to start the development server:
    ng serve

After running the above commands, you should see a message similar to the following on your terminal:

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

You can now open your browser and navigate to http://localhost:4200 to see your Angular 7 application in action.

Implementing WebSocket in Angular 7

Now that we have our basic Angular 7 application set up, let’s move on to implementing WebSocket. To do this, we will be using the ‘ngx-websocket‘ library, which provides a simple and easy-to-use API for WebSocket communication.

Step 1: Installing the ‘ngx-websocket’ Library

The first step is to install the ‘ngx-websocket’ library using NPM. Open a terminal or command prompt and run the following command:

npm install ngx-websocket --save

This will install the ‘ngx-websocket’ library and add it as a dependency to your project’s ‘package.json’ file.

Step 2: Creating a WebSocket Service

Next, we need to create a service that will handle WebSocket communication in our Angular 7 application. This service will be responsible for establishing a WebSocket connection with the server, sending and receiving messages, and handling any errors that occur.

To create a new service, run the following command in your project directory:

ng generate service websocket

This will generate a new service file named ‘websocket.service.ts’ in the ‘src/app’ directory of your project.

Open the ‘websocket.service.ts’ file and add the following code:

import { Injectable } from '@angular/core';import { Observable } from 'rxjs/Observable';import { WebSocketSubject, webSocket } from 'rxjs/webSocket';

@Injectable({providedIn: 'root'})export class WebsocketService {private socket$: WebSocketSubject<any>;

constructor() {}

public connect(url: string): void {this.socket$ = webSocket(url);}

public send(message: any): void {this.socket$.next(message);}

public onMessage(): Observable<any> {return this.socket$.asObservable();}

public close(): void {this.socket$.complete();}}

Let’s go through this code step by step:

  • The ‘Injectable’ decorator is used to indicate that this service can be injected into other components or services.
  • The ‘WebSocketSubject’ and ‘webSocket’ classes are imported from the ‘rxjs/webSocket’ module. These classes provide a simple and easy-to-use API for WebSocket communication.
  • The ‘connect’ method is used to establish a WebSocket connection with the server. It takes a ‘url’ parameter, which is the URL of the WebSocket server.
  • The ‘send’ method is used to send a message over the WebSocket connection. It takes a ‘message’ parameter, which is the message to be sent.
  • The ‘onMessage’ method is used to listen for incoming messages on the WebSocket connection. It returns an Observable that emits the incoming messages.
  • The ‘close’ method is used to close the WebSocket connection.

Step 3: Using the WebSocket Service in a Component

Now that we have our WebSocket service set up, let’s use it in a component. For this example, we will create a simple chat application that allows users to send and receive messages in real-time.

Create a new component using the following command:

ng generate component chat

This will generate a new component file named ‘chat.component.ts’ in the ‘src/app’ directory of your project.

Open the ‘chat.component.ts’ file and add the following code:

import { Component, OnInit } from '@angular/core';import { WebsocketService } from '../websocket.service';

@Component({selector: 'app-chat',templateUrl: './chat.component.html',styleUrls: ['./chat.component.css']})export class ChatComponent implements OnInit {message: string = '';messages: string[] = [];

constructor(private websocketService: WebsocketService) {}

ngOnInit() {this.websocketService.connect('ws://localhost:8080/chat');

this.websocketService.onMessage().subscribe((message: string) => {this.messages.push(message);});}

sendMessage() {this.websocketService.send(this.message);this.message = '';}

ngOnDestroy() {this.websocketService.close();}}

Let’s go through this code step by step:

  • The ‘Component’ decorator is used to indicate that this is an Angular component.
  • The ‘WebsocketService’ is imported and injected into the component’s constructor.
  • The ‘message’ and ‘messages’ variables are used to hold the current message and the list of messages, respectively.
  • The ‘ngOnInit’ method is called when the component is initialized. It establishes a WebSocket connection with the server and listens for incoming messages using the ‘onMessage’ method.
  • The ‘sendMessage’ method is called when the user sends a message. It sends the message over the WebSocket connection using the ‘send’ method and clears the message input field.
  • The ‘ngOnDestroy’ method is called when the component is destroyed. It closes the WebSocket connection using the ‘close’ method.

Step 4: Creating a WebSocket Server

Finally, we need to create a WebSocket server that will receive and send messages to the client. For this example, we will be using the ‘ws’ library, which provides a simple and easy-to-use API for creating WebSocket servers.

Create a new file named ‘server.js’ in your project directory and add the following code:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {console.log('Client connected');

ws.on('message', function incoming(message) {console.log('Received message: %s', message);wss.clients.forEach(function each(client) {if (client !== ws && client.readyState === WebSocket.OPEN) {client.send(message);}});});

ws.on('close', function close() {console.log('Client disconnected');});});

Let’s go through this code step by step:

  • The ‘WebSocket’ class is imported from the ‘ws’ library.
  • A new ‘WebSocket.Server’ instance is created and bound to port 8080.
  • The ‘connection’ event is emitted when a client connects to the server. The ‘ws’ parameter is a WebSocket instance representing the client connection.
  • The ‘message’ event is emitted when a message is received from the client. The received message is broadcasted to all connected clients using the ‘send’ method.
  • The ‘close’ event is emitted when a client disconnects from the server.

Conclusion

In this article, we have explored how to implement WebSocket in an Angular 7 application using the ‘ngx-websocket’ library. We have created a simple chat application that allows users to send and receive messages in real-time. We have also created a WebSocket server using the ‘ws’ library. WebSocket is a powerful tool for creating real-time applications that require fast and efficient communication between the client and server.

FAQ

What is WebSocket?

WebSocket is a protocol that enables two-way communication between a client and a server over a single, long-lived connection. This allows real-time data to be transmitted without the need for continuously polling the server for updates.

What is Angular 7?

Angular 7 is the latest version of the Angular framework, which is developed and maintained by Google. It is a powerful tool for creating dynamic web applications with a clean and modular architecture.

What is ‘ngx-websocket’?

‘ngx-websocket’ is a library for Angular that provides a simple and easy-to-use API for WebSocket communication.

What is ‘ws’?

‘ws’ is a library for Node.js that provides a simple and easy-to-use API for creating WebSocket servers.