Giter Site home page Giter Site logo

ng-socket-io's Introduction

ng-socket-io

Build Status npm version npm downloads

Socket.IO module for Angular 2 and 4

Install

npm install ng-socket-io

How to use

Import and configure SocketIoModule

//...
import { SocketIoModule, SocketIoConfig } from 'ng-socket-io';

const config: SocketIoConfig = { url: 'http://localhost:8988', options: {} };

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SocketIoModule.forRoot(config) 
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We need to configure SocketIoModule module using the object config of type SocketIoConfig, this object accepts two optional properties they are the same used here io(url[, options]).

Now we pass the configuration to the static method forRoot of SocketIoModule

Using your socket Instance

The SocketIoModule provides now a configured Socket service that can be injected anywhere inside the AppModule.

import { Injectable } from '@angular/core';
import { Socket } from 'ng-socket-io';

@Injectable()
export class ChatService {

    constructor(private socket: Socket) { }

    sendMessage(msg: string){
        this.socket.emit("message", msg);
    }
    
    getMessage() {
        return this.socket
            .fromEvent("message")
            .map( data => data.msg );
    }
}

Using multiple sockets with different end points

In this case we do not configure the SocketIoModule directly using forRoot. What we have to do is: extend the Socket service, and call super() with the SocketIoConfig object type (passing url & options if any).

import { Injectable, NgModule } from '@angular/core';
import { Socket } from 'ng-socket-io';

@Injectable()
export class SocketOne extends Socket {

    constructor() {
        super({ url: 'http://url_one:portOne', options: {} });
    }

}

@Injectable()
export class SocketTwo extends Socket {

    constructor() {
        super({ url: 'http://url_two:portTwo', options: {} });
    }

}

@NgModule({
  declarations: [
    //components
  ],
  imports: [
    SocketIoModule,
    //...
  ],
  providers: [SocketOne, SocketTwo],
  bootstrap: [/** AppComponent **/]
})
export class AppModule { }
 

Now you can inject SocketOne, SocketTwo in any other services and / or components.

API

Most of the functionalities here you are already familiar with.

The only addition is the fromEvent method, which returns an Observable that you can subscribe to.

socket.on(eventName: string)

Takes an event name and callback. Works the same as in Socket.IO.

socket.removeListener(eventName: string, callback: Function)

Takes an event name and callback. Works the same as in Socket.IO.

socket.removeAllListeners(eventName: string)

Takes an event name. Works the same as in Socket.IO.

socket.emit(eventName:string, message: any, [callback: Function])

Sends a message to the server. Optionally takes a callback. Works the same as in Socket.IO.

socket.fromEvent<T>(eventName: string): Observable<T>

Takes an event name and returns an Observable that you can subscribe to.

socket.fromEventOnce(eventName: string): Promise

Takes an event name, and returns a Promise instead of an Observable. Works the same as once in Socket.IO.

You should keep a reference to the Observable subscription and unsubscribe when you're done with it. This prevents memory leaks as the event listener attached will be removed (using socket.removeListener) ONLY and when/if you unsubscribe.

If you have multiple subscriptions to an Observable only the last unsubscription will remove the listener.

Example

You can also see this example with express.js.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

import { SocketIoModule, SocketIoConfig, Socket} from 'ng-socket-io';

const config: SocketIoConfig = { url: 'http://localhost:8988', options: {} };

@Injectable()
class ChatService {

    constructor(private socket: Socket) { }

    sendMessage(msg: string){
        this.socket.emit("message", msg);
    }

    getMessage() {
        return this.socket
            .fromEvent<any>("message")
            .map(data => data.msg );
    }
    
    close() {
      this.socket.disconnect()
    }
}


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SocketIoModule.forRoot(config) 
  ],
  providers: [ChatService],
  bootstrap: [AppComponent]
})
export class AppModule { }

LICENSE

MIT

ng-socket-io's People

Contributors

alan-agius4 avatar bluzi avatar ffreitasit avatar css-ianm avatar sensui7 avatar embarq avatar

Watchers

James Cloos avatar Yewei Jia avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.