Last active
February 10, 2019 21:05
-
-
Save pcnate/07ca6e1d7b709744814e4731eb24bb8c to your computer and use it in GitHub Desktop.
basic socket service for angular 6 and 7
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 { BrowserModule } from '@angular/platform-browser'; | |
import { NgModule } from '@angular/core'; | |
import { AppComponent } from './app.component'; | |
import { SocketService } from './_services'; | |
@NgModule({ | |
declarations: [], | |
imports: [ | |
BrowserModule, | |
], | |
entryComponents: [], | |
providers: [ | |
SocketService, | |
], | |
exports: [ | |
], | |
bootstrap: [AppComponent] | |
}) | |
export class AppModule { } |
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 { Subject, Observable } from '../../../node_modules/rxjs'; | |
import * as io from 'socket.io-client'; | |
@Injectable({ providedIn: 'root' }) | |
export class SocketService { | |
private url: String = ''; | |
private socket; | |
private socketSubject = new Subject(); | |
constructor() { | |
this.socket = io( this.url ); | |
} | |
public sendMessage( message ) { | |
this.socket.emit( 'new-message', message ); | |
} | |
public getMessages = () => { | |
return Observable.create( observer => { | |
this.socket.on('channelUpdate', message => { | |
observer.next( message ); | |
}); | |
}); | |
} | |
/** | |
* return observable | |
*/ | |
listenForAuthenticationChanges(): Observable<any> { | |
return this.socketSubject.asObservable(); | |
} | |
/** | |
* check for query string and return a better url if present | |
* | |
* @param url router url | |
*/ | |
private getReturnUrl( url: string ) { | |
return ''; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment