npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ngx-spad-lib-event-bus

v1.0.2

Published

## Tecnologías Implementadas

Readme

SPAD Cloud - Librería Event Bus

Tecnologías Implementadas

Angular CLI versión 17.3.8

Node.js versión 20.13.1

RxJs versión 7.8.0

@ngx-translate/core versión 15.x+

@ngx-translate/http-loader versión 8.x+

Descripción General

Esta librería contiene los siguientes módulos:

  • Módulo Event Bus: Contiene el servicio de eventos que permiten la comunicación entre diferentes aplicaciones de SPAD Cloud.

  • Módulo Interceptor: Contiene los métodos para interceptar las solicitudes HTTP y realizar las acciones correspondientes de acuerdo al código de estado de la respuesta.

  • Módulo Localización: Contiene los servicios y componentes para la localización de las aplicaciones de SPAD.

Instalación

npm install ngx-spad-lib-event-bus

Módulo Event Bus

Este módulo se desarrolla con el objetivo de implementar Programación Reactiva o basada en eventos, utilizando la librería RxJs para facilitar una comunicación eficiente entre las diversas aplicaciones de SPAD Cloud. Su principal propósito es apoyar la implementación de la Arquitectura de Micro frontends, permitiendo una integración fluida y desacoplada entre las aplicaciones, donde los eventos son manejados de manera reactiva, mejorando así la escalabilidad y la mantenibilidad de la aplicación.

Ejemplo de Uso: Emitir un evento

import {EventBusService} from "ngx-spad-lib-event-bus";

private readonly eventBusServices = inject(EventBusService)

this.eventBusServices.emit({
  name: 'pageChange',
  source: 'host',
  payload: { page }
})

Donde:

  • name: El nombre del evento que se desea emitir.
  • source: El identificador de la fuente del evento.
  • payload: Los datos asociados al evento.

Ejemplo de Uso: Emitir un evento con acciones específicas

import {EventBusService} from "ngx-spad-lib-event-bus";

private readonly eventBusServices = inject(EventBusService)

this.eventBusServices.registerConfig({
  source: 'host',
  eventName: 'paginationData',
  actions: [
    {
      name: 'updatePaginationUrls',
      payload: '',
      eventPayload: ''
    }
  ]
})

Donde:

  • source: El identificador de la fuente del evento.
  • eventName: El nombre del evento que se desea emitir.
  • actions: La lista de acciones asociadas al evento.

Ejemplo de Uso: Suscribirse a un evento

import {EventBusService} from "ngx-spad-lib-event-bus";

private readonly eventBusServices = inject(EventBusService)

this.eventBusService.on('pageChange', (event) => {
  const page = event.payload.page || 1
  
  this.updateTable(page)
})

El método on se utiliza para suscribirse al evento, especificando el nombre del evento y la función que se ejecutará cuando se emita el evento.

Nota: La función o acción a realizar que se indica en el código anterior es un ejemplo, pero no es una función asociada directamente al método on de eventBusService.

Ejemplo de Uso: Cancelar la suscripción de un evento

import {EventBusService} from "ngx-spad-lib-event-bus";

private readonly eventBusServices = inject(EventBusService)

this.eventBusServices.off('pageChange')

El método off se utiliza para cancelar la suscripción al evento, especificando el nombre del evento.

Módulo Localización (i18n)

El módulo Localization utiliza la librería ngx-translate para implementar internacionalización (i18n) en las aplicaciones de SPAD Cloud. Proporciona una estructura escalable para traducir la interfaz del usuario a múltiples idiomas.

Configuración del Módulo

Configuración Principal

Importar y configurar el módulo en el archivo app.config.ts de la aplicación.

import { importProvidersFrom } from '@angular/core';

import { LocalizationModule } from 'ngx-spad-lib-event-bus';

export const appConfig: ApplicationConfig = {
  providers: [
    importProvidersFrom(LocalizationModule.forRoot()),
  ],
};

Configuración de los Assets

En el archivo angular.json, agregar los assets de la librería.

"architect": {
  "build": {
    "options": {
      "assets": [
        {
          "glob": "**/*",
          "input": "./node_modules/ngx-spad-lib-event-bus/assets",
          "output": "/assets/"
        }
      ]
    }
  }
}

Archivos de Traducción

Crear los archivos JSON para cada idioma soportado en la carpeta assets/i18n/ de la aplicación. Se debe mantener las mismas claves (keys) en todos los archivos.

Ejemplo: en.json

{
  "MENU-APPS": {
    "IOT": "Environmental Risk Management",
    "LINE": "Facial and Gesture Recognition"
  }
}

Ejemplo: es.json

{
  "MENU-APPS": {
    "IOT": "Gestión del riesgo ambiental",
    "LINE": "Reconocimiento facial y de gestos"
  }
}

Cambio de Idioma

Uso del Componente LanguageSwitcherComponent

Este componente permite cambiar entre idiomas. Se puede utilizar el diseño por defecto o uno personalizado.

Importar el Componente

import { LanguageSwitcherComponent } from 'ngx-spad-lib-event-bus';

@Component({
  selector: 'app-header',
  standalone: true,
  imports: [LanguageSwitcherComponent],
  templateUrl: './header.component.html',
  styleUrl: './header.component.scss',
})
export class HeaderComponent { }

Ejemplo de Uso: Estilo por Defecto

<ngx-spad-lib-language-switcher
  [enTitle]="enTitle"
  [esTitle]="esTitle">
</ngx-spad-lib-language-switcher>

Ejemplo de Uso: Estilo personalizado con botones

<ngx-spad-lib-language-switcher
  [enTitle]="enTitle"
  [esTitle]="esTitle">
  <ng-template #customTemplate let-langData>
    <div class="custom-buttons">
      <button
        *ngFor="let lang of langData.languages"
        [class.active]="langData.language === lang.code"
        (click)="langData.toggle(lang.code)">
        <img *ngIf="lang.flag" [src]="lang.flag" [alt]="lang.name">
        {{lang.name}}
      </button>
    </div>
  </ng-template>
</ngx-spad-lib-language-switcher>

Configuración en el archivo ts:

import { LanguageSwitcherComponent, AvalibleLanguagesInterface } from 'ngx-spad-lib-event-bus';

@Component({
  selector: 'app-header',
  standalone: true,
  imports: [LanguageSwitcherComponent],
  templateUrl: './header.component.html',
  styleUrl: './header.component.scss',
})
export class HeaderComponent {
  myLanguages: AvalibleLanguagesInterface[] = [
    { code: 'es', name: 'Español', flag: 'path/to/flag'  },
    { code: 'en', name: 'English', flag: 'path/to/flag'  }, // La propiedad flag es opcional
  ];
}

Ejemplo de Uso: Estilo personalizado con lista desplegable

<ngx-spad-lib-language-switcher
  [enTitle]="enTitle"
  [esTitle]="esTitle"
  [availableLanguages]="myLanguages">
  <ng-template #customTemplate let-langData>
    <div class="custom-dropdown">
      <select
        [value]="langData.language"
        (change)="handleLanguageChange($event, langData.toggle)">
        <option
          *ngFor="let lang of langData.languages"
          [value]="lang.code">
          {{lang.name}}
        </option>
      </select>
    </div>
  </ng-template>
</ngx-spad-lib-language-switcher>

En el archivo ts:

import { LanguageSwitcherComponent, AvalibleLanguagesInterface } from 'ngx-spad-lib-event-bus';

@Component({
  selector: 'app-header',
  standalone: true,
  imports: [LanguageSwitcherComponent],
  templateUrl: './header.component.html',
  styleUrl: './header.component.scss',
})
export class HeaderComponent {
  myLanguages: AvalibleLanguagesInterface[] = [
    { code: 'es', name: 'Español', flag: 'path/to/flag'  },
    { code: 'en', name: 'English', flag: 'path/to/flag'  }, // La propiedad flag es opcional
  ];

  handleLanguageChange(event: Event, toggleFn: (lang: string) => void) {
    const select = event.target as HTMLSelectElement;
    toggleFn(select.value);
  }
}

Uso en Componentes

Importación del Módulo

import { LocalizationModule, ChangeLanguageComponent } from 'ngx-spad-lib-event-bus';

@Component({
  selector: 'app-header',
  standalone: true,
  imports: [LocalizationModule, ChangeLanguageComponent],
  templateUrl: './header.component.html',
  styleUrl: './header.component.scss',
})
export class HeaderComponent { }

Traducción en Plantillas

<p>{{ 'home.title' | translate }}</p>

Contenido Dinámico

<ngx-spad-lib-change-language [translationKey]="'home.description'"></ngx-spad-lib-change-language>

Cargar Imágenes Según Idioma

Configurar en el archivo ts:

import { LocalizationModule, ChangeLanguageComponent, ChangeLanguageService } from 'ngx-spad-lib-event-bus';

@Component({
  selector: 'app-header',
  standalone: true,
  imports: [LocalizationModule, ChangeLanguageComponent, ChangeLanguageService],
  templateUrl: './header.component.html',
  styleUrl: './header.component.scss',
})
export class HeaderComponent {
  private readonly changeLanguageService = inject(ChangeLanguageService);

  get currentLang(): string {
    return this.changeLanguageService.getCurrentLang();
  }
}

Uso en el archivo HTML:

<img [src]="currentLang !== 'en' ? 'path-images' : 'path-images'" alt="image" />

Uso del Módulo Interceptor

El interceptor proporciona un manejo centralizado de las solicitudes HTTP y realizar las acciones correspondientes de acuerdo al tipo de error: 401 Unauthorized, 400 Bad Request y 500 Internal Server Error de todas las peticiones que realice la aplicación.

Configuración de los Endpoints

Crear un archivo de tipo IApiConfig el cual debe contener la configuración de los endpoints, siguiendo la estructura:

import { IApiConfig } from "ngx-spad-lib-event-bus";

export const API_CONFIG: IApiConfig = {
  endpoints: {
    contact: {
      url: environment.API_CONTACT,
      reqAuthorization: true,
      methods: ['POST'],
    },
    viewDemo: {
      url: environment.API_VIEW_DEMO_URL,
      reqAuthorization: false,
    },
  },
};

Donde:

  • endpoints: El objeto que contiene la configuración de los endpoints.
  • contact: El nombre del endpoint.
  • url: La URL del endpoint.
  • reqAuthorization: Indica si la solicitud necesita autorización.
  • methods: La lista de methods HTTP permitidos.

Configuración del Interceptor

Configurar el provider en el archivo app.config.ts de la aplicación donde se instala la librería.

import { provideInterceptor } from "ngx-spad-lib-event-bus";

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptors([AuthorizationInterceptor])),
    provideInterceptor({
      apiConfig: {
        endpoints: API_CONFIG.endpoints
      },
      tokenUrl: environment.API_AUTHORIZATION_URL,
      clientCredentials: {
        grant_type: import.meta.env['NG_APP_GRANT_TYPE'],
        client_id: import.meta.env['NG_APP_CLIENT_ID'],
        client_secret: import.meta.env['NG_APP_CLIENT_SECRET'],
      }
    }),
  ],
};

Configuración del Token

Si la aplicación lo requiere, inicializar en el componente app.component.ts el token de autenticación.

import {AuthorizationUseCase} from "ngx-spad-lib-event-bus";

export class AppComponent {
  private readonly authorizationUseCase = inject(AuthorizationUseCase);

  ngOnInit(): void {
    this.initializeToken();
  }

  private initializeToken(): void {
    if (!this.authorizationUseCase.getStoredToken()) {
      this.subscription = this.authorizationUseCase.getToken().subscribe();
    }
  }
}

Manejo de Errores

Los errores 400 Bad Request y 500 Internal Server Error son capturados automáticamente por el interceptor. Su implementación puede realizarse de la siguiente manera:

yourUseCase(): Observable<any> {
  return this.yourService.yourMethod().pipe(
    // Lógica del use case
    catchError((error) => {
      // Lógica para manejar el error
    })
  )
}

Notas Importantes

  • El interceptor maneja los errores para todas las peticiones HTTP que realice la aplicación independiente de si requiere autorización o no.

  • Para endpoints que requieren autorización (reqAuthorization: true), él token se maneja automáticamente.

  • Los errores 401 Unauthorized se realiza la renovación automática del token.