ng6-socket.io
Socket.IO module for Angular 6 and RxJS 6.
This is a fork of ng-socket-io as it wasn't being actively maintained. Credit to original author Bougarfaoui El Houcine.
Install
npm install ng6-socket-io
How to use
Angular 6 Note:
For use with Angular 6+ and RxJS 6+ add the following line to polyfills.ts
// src/polyfills.tswindow as any.global = window;
Import and configure SocketIoModule
//...; ;
We need to configure SocketIoModule
module using the object config
of type SocketIoConfig
, this object accepts two optional properties they are the same used here io(url[, options]).
Now we pass the configuration to the static method forRoot
of SocketIoModule
Using your socket Instance
The SocketIoModule
provides now a configured Socket
service that can be injected anywhere inside the AppModule
.
;;
Using multiple sockets with different end points
In this case we do not configure the SocketIoModule
directly using forRoot
. What we have to do is: extend the Socket
service, and call super()
with the SocketIoConfig
object type (passing url
& options
if any).
;;
Now you can inject SocketOne
, SocketTwo
in any other services and / or components.
API
Most of the functionality here you are already familiar with.
The only addition is the fromEvent
method, which returns an Observable
that you can subscribe to.
socket.on(eventName: string)
Takes an event name and callback. Works the same as in Socket.IO.
socket.removeListener(eventName: string, callback: Function)
Takes an event name and callback. Works the same as in Socket.IO.
socket.removeAllListeners(eventName: string)
Takes an event name. Works the same as in Socket.IO.
socket.emit(eventName:string, message: any, [callback: Function])
Sends a message to the server. Optionally takes a callback. Works the same as in Socket.IO.
socket.fromEvent<T>(eventName: string): Observable<T>
Takes an event name and returns an Observable that you can subscribe to.
socket.fromEventOnce(eventName: string): Promise
Takes an event name, and returns a Promise instead of an Observable.
Works the same as once
in Socket.IO.
You should keep a reference to the Observable subscription and unsubscribe when you're done with it.
This prevents memory leaks as the event listener attached will be removed (using socket.removeListener
) ONLY and when/if you unsubscribe.
If you have multiple subscriptions to an Observable only the last unsubscription will remove the listener.
Example
You can also see this example with express.js.
Go to /examples/chat-app/public and run ng build
Start both servers in separate terminals with node app1.js
and access the page from http://localhost:8988/
;;; ; ;; ;
LICENSE
MIT