In this article we will discuss how to combine socket.io with RxJs Observables in Angular.
We will implement a simple chat feature using socket based communication between client and server. Socket.io will take care of setting up the socket, but we will be using observables to receive and distribute chat messages from the server.
The goal is to build a chat server where we can open multiple browser windows and be able to send chat messages between the different browsers.
First we will define a simple server using nodeJs/express.
The server is responsible for managing connections and notifying connected clients of new chat messages.
In order to open a channel between client and server we have to initiate a socket connection from the client.
We want to encapsulate the socket communication in an observable, so the first step is to create ChatService where we define our observable.
The observable is configured to emit a value every time we receive a new chat message from the server. By calling observer.next(), subscribers to our observable will be notified of the new message.
We want to be able to disconnect from the chat, so our observable returns a subscription object that we can use to unsubscribe and break the connection.
Next we will create a component for the chat application.
The UI is simple with a just a textbox and a button. However, the important part to pay attention to is the subscription to the observable returned from chatService.getMessages().
The observable will emit a new value for every new chat message and update our list of displayed messages.
Any message sent via the UI is distributed to all connected clients – including the client who sent the message.
I have put the source code on Github.