angular2-websocket-service
An rxjs stream based websocket factory service, ideal for use with angular 2.
How to install (with webpack/angular-cli)
Install the dependency:
npm install -S angular2-websocket-service# the following dependency is recommended for most users npm install -S queueing-subject
Import the service in your app.module.ts
or equivalent:
How to use with angular 2
Add the service to your module's providers list:
@ {}
You can write your own service to provide a websocket using this factory as follows:
// file: server-socket.service.ts @ private inputStream: QueueingSubject<any> public outputStream: Observable<any> {} public { if thisoutputStream return thisoutputStream // Using share() causes a single websocket to be created when the first // observer subscribes. This socket is shared with subsequent observers // and closed when the observer count falls to zero. return thisoutputStream = thissocketFactory } public :void // If the websocket is not connected then the QueueingSubject will ensure // that messages are queued and delivered when the websocket reconnects. // A regular Subject can be used to discard messages sent when the websocket // is disconnected. thisinputStreamnextmessage
This service could be used like this:
@ private socketSubscription: Subscription { const stream = thissocket thissocketSubscription = stream // send message to server, if the socket is not connected it will be sent // as soon as the connection becomes available thanks to QueueingSubject thissocket } { thissocketSubscription }