Created
March 29, 2017 13:30
-
-
Save amcdnl/36ea71dcb09033736637e1e6775f9d3e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { Observable } from 'rxjs/Observable'; | |
import * as io from 'socket.io-client'; | |
@Injectable() | |
export class SocketService { | |
socket: any; | |
private host: string = `${window.location.protocol}//${window.location.hostname}:${window.location.port}`; | |
constructor() { | |
this.socket = io(this.host); | |
this.socket.on('error', (error: string) => { | |
throw new Error(`Sockets: ${error}`); | |
}); | |
} | |
on(event: string): Observable<any> { | |
return new Observable((observer) => { | |
this.socket.on(event, (data) => { | |
observer.next(data); | |
}); | |
}); | |
} | |
emit(name, data): void { | |
this.socket.emit(name, data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use similar to this but store the observable for future returns so as to not generate excess listeners.
So far I've found it to be really reliable. Shutting down the listener on unsubscribes is a nice plus, too.