Putting the pattern into action

Now that we know how to create a connection to our ws endpoint, it’s time to explore the different steps to consume real-time messages. The first step is isolating all interactions with WebSocketSubject in a separate Angular service.

Step 1: Creating a real-time service

We’ll create an Angular service called RealTimeService under src/app/core/services. In this service, we’ll start by creating the following:

  • A private property, socket$, that will contain the reference to the WebSocket subject that we’ll create in the getNewWebSocket() method.

  • A private method, getNewWebSocket(), that returns WebSocketSubject, produced by the webSocket factory function that takes WS_ENDPOINT as input. The WS_ENDPOINT is a constant that contains the value of the wsEndpoint property available in the environment file. The URL of the endpoints can change from one environment to another. That’s why it’s recommended to put that information in the environment files.

  • A public method, sendMessage(), that sends a message given as input to the socket, which will forward the message to the server.

  • A public method, close(), that closes the connection by completing the subject.

This is how the code of RealTimeService will look after putting all these pieces together in file recipes-book-front/src/app/core/services/real-time.service.ts:

Get hands-on with 1400+ tech skills courses.