rxjs-websockets
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 rxjs-websockets
npm install -S queueing-subject
Import the service in your app.module.ts
or equivalent:
How to use with angular 2
You can write your own service to provide a websocket using this factory as follows:
import { Injectable } from '@angular/core'
import { QueueingSubject } from 'queueing-subject'
import { Observable } from 'rxjs/Observable'
import websocketConnect from 'rxjs-websockets'
@Injectable()
export class ServerSocket {
private inputStream: QueueingSubject<any>
public outputStream: Observable<any>
public connect() {
if (this.outputStream)
return this.outputStream
return this.outputStream = websocketConnect(
'ws://127.0.0.1:4201/ws',
this.inputStream = new QueueingSubject<any>()
).share()
}
public send(message: any):void {
this.inputStream.next(message)
}
}
This service could be used like this:
import { Component } from '@angular/core'
import { Subscription } from 'rxjs/Subscription'
import { ServerSocket } from './server-socket.service'
@Component({
selector: 'socket-user',
templateUrl: './socket-user.component.html',
styleUrls: ['./socket-user.component.scss']
})
export class SocketUserComponent {
private socketSubscription: Subscription
constructor(private socket: ServerSocket) {
const stream = this.socket.connect()
this.socketSubscription = stream.subscribe(message:any => {
console.log('received message from server: ', message)
})
this.socket.send({ type: 'helloServer' })
}
ngOnDestroy() {
this.socketSubscription.unsubscribe()
}
}