Skip to content

Instantly share code, notes, and snippets.

@pcnate
Last active February 10, 2019 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcnate/07ca6e1d7b709744814e4731eb24bb8c to your computer and use it in GitHub Desktop.
Save pcnate/07ca6e1d7b709744814e4731eb24bb8c to your computer and use it in GitHub Desktop.
basic socket service for angular 6 and 7
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 { }
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