WebSocket in Angular & How to Build Real-Time Applications

How to establish a bidirectional client-server connection and build a real-time Angular application with the WebSocket protocol

In this article, we will study how to use WebSocket in Angular to create a real-time application. In the process, we will explore some RxJS operators.

Modern web applications need to perform client-server communication to get things done. Most of them use the HTTP protocol — or more precisely its secure version (HTTPS).

However, the HTTP protocol is not always the perfect match for all types of applications, such as chatting or real-time applications. This is where WebSocket comes into play.

Let’s get started!

A Few Words Before the Action

Both HTTP and WebSocket are client-server communication protocols but work differently.

HTTP is unidirectional and stateless.

  • Unidirectional because the connection is always established on the client’s initiative. The client sends a request, the server responds, and the connection between them is terminated.

  • Stateless because each request is independent and has no knowledge of the request(s) that came before it.

WebSocket is bidirectional and stateful.

  • Bidirectional because it allows data to be sent from the client to the server and vice versa.

  • Stateful because the connection between client and server will remain alive until it is terminated by either one of them.

HTTP has http:// as a prefix, while its secure version (HTTPS) uses https://. Respectively, WebSocket has a unique prefix — it starts with ws://. There is also a secure version of the protocol that starts with wss://.

For our demo, we will use the plain version of WebSocket. However, for any real-world application, you should always use the secure version.

Ok, let’s jump into action!

Using WebSocket in Angular

The demo application is quite simple. It consists of an interval selector and a chart.

The user can select an interval from a set of predefined values. The app will receive and update the chart based on the selected value.

Screenshot of the application

The Client-Side

Let’s start simple — baby steps!

We create a service that will hold the WebSocketSubject. We will use this to both send and receive messages through a WebSocket connection.

WebSocket service snippet.
  • On line 3, we have the URL — for WebSocket, it starts with ws://.

  • On line 4, we use the webSocket factory function to get a WebSocketSubject.

  • On line 5, we use asObservable to get an observable with the webSocketSubject as its source.

  • On lines 7–9, we define the updateInterval method. Sending data to the server is as simple as calling webSocketSubject.next().

Next, we subscribe to the observable to get data from the server. We also do some error handling and try to reconnect in case the connection drops.

Getting data from the server by subscribing to the WebSocket.

Let’s walk through this snippet.

  • On lines 7–10, we use catchError to reset the interval to its default value in case of an error (hint: disconnect). We re-throw the error using throwError as we don’t want the observable to complete.

  • On line 11, we use the retry operator. We want to try to re-subscribe to the source observable in case of an error. We want to try every 5 seconds, indefinitely.

  • On line 12, we use the takeUntilDestroyed operator to automatically unsubscribe when the component is destroyed. Note that this operator is in developer preview in Angular v16.

  • On lines 14–19, we subscribe to render the newly received values.

Explaining the details of the ChartService is out of the scope of this article — you can find the source code at the end of this article if you want to study it. You can also check this article if you are interested in charts.

Ok, that’s it — the client-side is ready!

The Server-Side

For the client to receive data, there has to be a server.

Don’t worry, we’ve got you covered!

We prepared a simple server so you can see everything in action.

Assuming you are in the root directory of the demo, just run the following commands.

cd server
npm install
node src/server.js

A message will confirm that the server is up and running.

Then open up your browser at localhost:4200. You should see the chart update in real-time!

You can find the source code in this GitHub repository.

Conclusion

WebSocket allows bidirectional and stateful communication, which makes it ideal for real-time applications.

RxJS provides a module that contains the webSocket function. The function returns a WebSocketSubject. Use this Subject to exchange data with the server.

Send data by using the next method of the Subject. Read data by subscribing to an observable with that Subject as its source.

That sums up how to use WebSocket in Angular.

Thanks for reading.