Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ngx-socket-io

rodgc150kMIT4.8.5TypeScript support: included

Socket.IO module for Angular

Angular, Socket-io, TypeScript

readme

ngx-socket-io

Build Status npm version npm downloads

Socket.IO module for Angular

Install

npm install ngx-socket-io

Important:

Make sure you're using the proper corresponding version of socket.io on the server.

Package Version Socket-io Server Version Angular version
v3.4.0 v2.2.0
v4.1.0 v4.0.0 12.x
v4.2.0 v4.0.0 13.x
v4.3.0 v4.5.1 14.x
v4.4.0 v4.5.1 15.x
v4.5.0 v4.5.1 16.x
v4.6.1 v4.7.2 17.x
v4.7.0 v4.7.2 18.x
v4.8.1 v4.8.1 19.x

How to use

Import and configure SocketIoModule for NgModule based applications

import { SocketIoModule, SocketIoConfig } from 'ngx-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

Import and configure SocketIoModule for standalone based applications

In app.config.ts use the following:

import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';

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

export const appConfig: ApplicationConfig = {
  providers: [provideSocketIo(config)],
};

In standalone applications, there is no AppModule to import SocketIoModule. Instead, we use provideSocketIo(config) directly in the providers' configuration. The usage of the socket instance remains the same as in an NgModule-based application.

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 'ngx-socket-io';
import { map } from 'rxjs/operators';

@Injectable()
export class ChatService {
  constructor(private socket: Socket) {}

  sendMessage(msg: string) {
    this.socket.emit('message', msg);
  }
  getMessage() {
    return this.socket.fromEvent('message').pipe(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 'ngx-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.of(namespace: string)

Takes a namespace and returns an instance based on the current config and the given namespace, that is added to the end of the current url. See Namespaces - Client Initialization. Instances are reused based on the namespace.

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

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, ...args: any[])

Sends a message to the server. 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.fromOneTimeEvent<T>(eventName: string): Promise<T>

Creates a Promise for a one-time event.

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.

Know Issue

For error TS2345 you need to add this to your tsconfig.json.

{
  ...
  "compilerOptions": {
    ...
    "paths": {
      "rxjs": ["node_modules/rxjs"]
    }
  },
}

LICENSE

MIT

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

[4.8.5] - 2025-04-07

Update

  • Providers to use providerSocketIo function that is using makeEnvironmentProviders instance of importProvidersFrom

[4.8.4] - 2025-02-09

Changed

  • Updated the options property in the SocketIoConfig interface to use Partial<ManagerOptions> instead of a custom-defined object.

[4.8.3] - 2025-02-06

Fixed

  • off() behavior, sync with socket-io-client and takes a single function, not array
  • Mark internal fields as private in WrappedSocket.

Removed

  • Outdated @types/socket-io & @types/socket.io-client dependencies and use the built-in types instead.

[4.8.2] - 2024-12-27

Added

  • Return types to help users.
  • emitWithAck().
  • offAny().
  • offAnyOutgoing().
  • send().
  • compress().
  • export SOCKET_CONFIG_TOKEN.

Fixed

  • socket.of() method.
  • Chaining methods.
  • Volatile usage.
  • connect() and disconnect() arguments.

[4.8.1] - 2024-11-25

Update

  • Bump @angular/core dependencies to v19.0.0.

[4.8.0] - 2024-11-21

Update

  • Bump @angular dependencies to v19.0.0.

[4.7.0] - 2024-05-24

Update

  • Bump @angular dependencies to v18.0.0.
  • Bump ng-packagr dependencies to v18.0.0.
  • Bump typescript dependencies to v5.4.0.

[4.6.1] - 2023-11-09

Fixed

  • Compatibility with future MINOR versions of Angular.

[4.6.0] - 2023-11-08

Added

  • Optional callback to ioSocket.connect method.

Update

  • Bump @angular dependencies to v17.0.0.
  • Bump ng-packagr dependencies to v17.0.0.
  • Bump postcss dependencies to 8.4.31.
  • Bump zone.js dependencies to 0.14.0.
  • Bump socket.io dependencies to 4.7.2.
  • Bump socket.io-client dependencies to 4.7.2.
  • Bump @types/socket.io dependencies to 2.1.13.
  • Bump @types/socket.io-client dependencies to 1.4.36.

[4.5.1] - 2023-05-11

Added

  • listeners Method.
  • listenersAny Method.
  • listenersAnyOutgoing Method.
  • off Method.
  • onAny Method.
  • onAnyOutgoing Method.
  • prependAny Method.
  • prependAnyOutgoing Method.
  • timeout Method.
  • volatile Method.

[4.5.0] - 2023-05-11

Added

  • forceNew option

Update

  • Bump @angular dependencies to v16.0.0.
  • Bump ng-packagr dependencies to v16.0.0.

[4.4.0] - 2022-11-17

Update

  • Bump @angular dependencies to v15.0.0.
  • Bump ng-packagr dependencies to v15.0.0.
  • Bump typescript dependencies to v4.8.0.

[4.3.1] - 2022-09-12

Added

  • auth option to config
  • closeOnBeforeunload option to config

Fixed

  • Name function fromEventOnce to fromOneTimeEvent

[4.3.0] - 2022-06-28

Update

  • Bump @angular dependencies to v14.0.0.
  • Bump socket.io dependencies to v4.5.1.
  • Bump socket.io-client dependencies to v4.5.1.

[4.2.0] - 2021-10-22

Update

  • Bump @angular dependencies to v13.0.0.

Fixed

  • Property withCredentials is missing in type.

[4.1.0] - 2021-6-29

Added

  • Husky

Update

  • Bump @angular dependencies to v12.0.0.

[4.0.0] - 2021-3-29

Update

  • Bump socket.io dependencies to v4.0.0.
  • Bump socket.io-client dependencies to v4.0.0.

[3.3.1] - 2021-3-29

Change

  • Downgrade socket.io dependencies to v2.2.0.
  • Downgrade socket.io-client dependencies to v2.2.0.

[3.3.0] - 2021-3-12

Updated

  • Bump Angular dependencies to version 11.
  • Bump socket.io dependencies to v4.0.0.
  • Bump socket.io-client dependencies to v4.0.0.

[3.2.0] - 2020-06-26

Updated

  • Angular dependencies to version 10.

Changed

emit() to accept any numbers of args.

[3.1.0] - 2020-06-26

Updated

  • Angular dependencies to version 9.

Fixed

  • tslint warnings.

[3.0.0] - 2019-08-10

Updated

  • Angular dependencies to version 8.

Changed

  • Pack library to ng-packagr from ngc-rollup.

Fixed

  • Errors at packing the library.

Removed

  • rxjs from dependencies.
  • @Inject(SOCKET_CONFIG_TOKEN) form service constructor, casuing erros with Angular 8.

[2.1.1] - 2018-11-28

Added

  • Function to create custom namespaces.

Changed

  • Angular peer dependencie to ^6.0.0 || ^7.0.0 to resolve npm warnings.

Removed

  • Steps to run proyect in Anuglar 6 with version 1.0.8.

[2.0.0] - 2018-10-26

Removed

  • Angular core from dependencies to work on Angular 7.