chaqui-catalog-frontend-lib
v1.1.30
Published
Librería Angular para consumir el servicio de catálogos, los componentes son standalone
Readme
Librería Angular - Catalog Lib
Librería Angular para consumir el servicio de catálogos de manera sencilla y configurable.
Características
- ✅ Servicio configurable para conectar con tu backend
- ✅ Componente reutilizable para seleccionar items de un catálogo
- ✅ Manejo robusto de errores
- ✅ Carga asincrónica de items
- ✅ Compatible con Angular 15+
- ✅ Totalmente tipado con TypeScript
Instalación
1. Instalar la librería en tu proyecto Angular
npm install catalog-libO si usas yarn:
yarn add catalog-libConfiguración
1. Importar el módulo en tu app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { CatalogModule } from 'catalog-lib';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpClientModule,
CatalogModule.forRoot({
apiBaseUrl: 'http://localhost:3001/api' // URL base de tu servicio
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }2. Uso en aplicaciones standalone (Angular 15+)
Si tu app usa bootstrapApplication y componentes standalone, no uses CatalogModule.forRoot(...) dentro de imports del componente.
Usa providers globales:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { provideCatalog } from 'catalog-lib';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(),
provideCatalog({
apiBaseUrl: 'http://localhost:3001/api'
})
]
});Y en tu componente standalone importa el componente de la librería directamente:
import { Component } from '@angular/core';
import { CatalogItemsSelectComponent } from 'catalog-lib';
@Component({
selector: 'app-example',
standalone: true,
imports: [CatalogItemsSelectComponent],
template: `<catalog-items-select [catalogId]="1"></catalog-items-select>`
})
export class ExampleComponent {}Uso
Opción 1: Usar el Componente
En tu componente:
import { Component } from '@angular/core';
import { CatalogItem } from 'catalog-lib';
@Component({
selector: 'app-example',
template: `
<catalog-items-select
[catalogId]="catalogId"
[selectedItemId]="selectedItemId"
catalogLabel="ID del Catálogo"
itemSelectPlaceholder="Selecciona un item"
(itemSelected)="onItemSelected($event)"
(error)="onError($event)"
></catalog-items-select>
<div *ngIf="selectedItem">
<h3>Item Seleccionado:</h3>
<p><strong>ID:</strong> {{ selectedItem.id }}</p>
<p><strong>Nombre:</strong> {{ selectedItem.name }}</p>
</div>
`
})
export class ExampleComponent {
catalogId: number = 1;
selectedItemId?: number;
selectedItem: CatalogItem | null = null;
onItemSelected(item: CatalogItem): void {
this.selectedItem = item;
console.log('Item seleccionado:', item);
}
onError(error: string): void {
console.error('Error:', error);
}
}Opción 2: Usar el Servicio Directamente
Si prefieres controlar la lógica manualmente:
import { Component, OnInit } from '@angular/core';
import { CatalogService, CatalogItem, Catalog } from 'catalog-lib';
@Component({
selector: 'app-example',
template: `
<div>
<input
type="number"
[(ngModel)]="catalogId"
(change)="loadItems()"
placeholder="ID del Catálogo"
/>
<select [(ngModel)]="selectedItemId" (change)="onItemSelected()">
<option value="">Selecciona un item</option>
<option *ngFor="let item of items" [value]="item.id">
{{ item.name }}
</option>
</select>
</div>
`
})
export class ExampleComponent implements OnInit {
catalogId: number = 1;
selectedItemId?: number;
items: CatalogItem[] = [];
selectedItem: CatalogItem | null = null;
constructor(private catalogService: CatalogService) {}
ngOnInit(): void {
this.loadItems();
}
loadItems(): void {
this.catalogService.getItemsByCatalogId(this.catalogId)
.subscribe({
next: (items) => {
this.items = items;
},
error: (error) => {
console.error('Error cargando items:', error);
}
});
}
onItemSelected(): void {
if (this.selectedItemId) {
this.selectedItem = this.items.find(item => item.id === this.selectedItemId) || null;
}
}
}API Reference
CatalogModule
Método forRoot(config: CatalogConfig)
Configura el módulo con la URL base del servicio.
Parámetros:
config.apiBaseUrl(string): URL base del servicio de catálogos. Ejemplo:http://localhost:3001/api
provideCatalog(config: CatalogConfig)
Configura la librería para aplicaciones standalone usando providers.
CatalogService
Método getCatalogs()
Obtiene todos los catálogos disponibles.
this.catalogService.getCatalogs().subscribe(
(catalogs: Catalog[]) => {
console.log('Catálogos:', catalogs);
}
);Método getItemsByCatalogId(catalogId: number)
Obtiene todos los items de un catálogo específico.
this.catalogService.getItemsByCatalogId(1).subscribe(
(items: CatalogItem[]) => {
console.log('Items:', items);
}
);Método getItemById(itemId: number)
Obtiene un item específico por su ID.
this.catalogService.getItemById(123).subscribe(
(item: CatalogItem) => {
console.log('Item:', item);
}
);CatalogItemsSelectComponent
Componente que proporciona una interfaz para seleccionar items de un catálogo.
Inputs
catalogId(number): ID del catálogo del cual cargar los itemsselectedItemId(number, opcional): ID del item actualmente seleccionadocatalogLabel(string, default: 'ID del Catálogo'): Label del input del catálogoitemSelectPlaceholder(string, default: 'Selecciona un item'): Placeholder del select de items
Outputs
itemSelected: Emite cuando se selecciona un item. Emite un objetoCatalogItemerror: Emite cuando hay un error al cargar los items. Emite un string con el mensaje de error
Modelos de Datos
Catalog
interface Catalog {
id: number;
name: string;
description?: string;
}CatalogItem
interface CatalogItem {
id: number;
catalogId: number;
name: string;
description?: string;
[key: string]: any; // Propiedades adicionales
}Ejemplos Avanzados
Ejemplo con manejo de errores
import { Component } from '@angular/core';
import { CatalogItem } from 'catalog-lib';
@Component({
selector: 'app-catalog-example',
template: `
<catalog-items-select
[catalogId]="catalogId"
(itemSelected)="onItemSelected($event)"
(error)="onError($event)"
></catalog-items-select>
<div *ngIf="errorMessage" class="alert alert-danger">
{{ errorMessage }}
</div>
<div *ngIf="selectedItem" class="alert alert-success">
Item seleccionado: {{ selectedItem.name }}
</div>
`
})
export class CatalogExampleComponent {
catalogId = 1;
selectedItem: CatalogItem | null = null;
errorMessage: string = '';
onItemSelected(item: CatalogItem): void {
this.selectedItem = item;
this.errorMessage = '';
}
onError(error: string): void {
this.errorMessage = error;
}
}Desarrollo
Para construir la librería:
npm run buildPara correr los tests:
npm run testLicencia
ISC
Autor
Desarrollado para el servicio de Catálogos
