Last active
October 26, 2018 10:32
-
-
Save luixaviles/25e8599770b722a3d463ec95aaff89e9 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 { Observer } from 'rxjs/Observer'; | |
import { Message } from '../model/message'; | |
import { Event } from '../model/event'; | |
import * as socketIo from 'socket.io-client'; | |
const SERVER_URL = 'http://localhost:8080'; | |
@Injectable() | |
export class SocketService { | |
private socket; | |
public initSocket(): void { | |
this.socket = socketIo(SERVER_URL); | |
} | |
public send(message: Message): void { | |
this.socket.emit('message', message); | |
} | |
public onMessage(): Observable<Message> { | |
return new Observable<Message>(observer => { | |
this.socket.on('message', (data: Message) => observer.next(data)); | |
}); | |
} | |
public onEvent(event: Event): Observable<any> { | |
return new Observable<Event>(observer => { | |
this.socket.on(event, () => observer.next()); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also you are missing the teardown on the onEvent so when you unsubscribe you don't keep the socket event listeners unnecessarily.
public onEvent(event:Event):Observable<any>{ return new Observable<Event>(observer =>{ const handler = (data)=>observer.next(data); this.socket.on(event,handler); return ()=>{this.socket.off(event,handler)} })
this way when you unsubscribe from onEvent you will tear down the event listener as well. Quite leaky this code here but a good starter for writing a service.