Using WebSockets with Angular and RxJS

WebSocket is a web communication protocol that allows two-way communication between a client and a server. What makes that technology appealing is that unlike regular TCP sockets, WebSockets use the same port as the HTTP protocol, which is port 80.

This means that when using WebSockets you don’t have to worry about firewalls blocking that port and preventing your data to flow between client and server. The technology has been around for a while, long enough to enjoy excellent support across all browsers according to caniuse.com:

This is image title

How to use WebSockets with RxJs?

This is actually almost too easy. You just have to import the webSocket function from RxJs, call it with the URL of your WebSocket, and… done!

import {webSocket, WebSocketSubject} from 'rxjs/webSocket';
myWebSocket: WebSocketSubject = webSocket('ws://localhost:8000');

You now have an RxJs subject (more info about subjects with this tutorial) that you can subscribe to in order to receive some data:

myWebSocket.asObservable().subscribe(dataFromServer => //...);

And if you want to send data to the server, simply use the next method of your subject:

myWebSocket.next({message: 'some message'});

Also note that when you subscribe to a WebSocket subject, you can register callbacks to be notified when an error happens or when the connection is closed, just like with a regular observable:

myWebSocket.subscribe(    
   msg => console.log('message received: ' + msg), 
   // Called whenever there is a message from the server    
   err => console.log(err), 
   // Called if WebSocket API signals some kind of error    
   () => console.log('complete') 
   // Called when connection is closed (for whatever reason)  
);

Thank you for reading !

If you enjoyed this post, please share it. Your help is always appreciated.

#angular #angular8 #typescript #rxjs #websocket

Using WebSockets with Angular and RxJS
244.15 GEEK