How to use WebSockets with RxJS and Angular?
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:

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)
);
My name is Alain Chautard. I am a Google Developer Expert in Angular, as well as founding consultant and trainer at Angular Training where I help development teams learn and become proficient with Angular.
Need help with Angular? Let’s schedule some time to talk. I provide coaching and on-site training.
If you enjoyed this Angular tutorial, please clap for it or share it. Your help is always appreciated.