http-request-manager
v18.13.1
Published
This is an Angular Module containing Components/Services using Material
Readme
HTTP Request Manager - Angular Library
A comprehensive Angular library providing enterprise-grade HTTP request management, state management, real-time communication, and local data persistence.
This README is the main documentation hub for the library. Detailed service guides live in src/docs/, and this page links to the observable/ngrx services for older Angular applications and the signal-based services for newer Angular applications in parallel.
🚀 Features
Core Capabilities
| Feature | Description | Angular 14-18 / Observable + NgRx | Angular 19+ / Signals |
|---------|-------------|----------------------------------|------------------------|
| 🌐 HTTP Request Management | Retry, polling, streaming, file downloads | HTTPManagerService | HTTPManagerSignalsService |
| 🔄 State Management | CRUD state, persistence, derived state | HTTPManagerStateService and StoreStateManagerService | StoreStateManagerSignalsService |
| 💬 Real-Time Communication | WebSocket channels, tracking, messaging | WebSocketManagerService, WebSocketMessageService, and MessageTrackerService | WebSocketSignalsManagerService and MessageTrackerSignalsService |
| 💾 Data Persistence | Local/session storage and offline caching | LocalStorageManagerService and DatabaseManagerService | LocalStorageSignalsManagerService |
| ⚡ Utility Functions | JSON handling, encryption, headers, validation, logging | UtilsService, Encryption, Logger | Uses the same utility layer |
Key Benefits
- ✅ Type-Safe - Full TypeScript support with generics
- ✅ Offline-First - Built-in IndexedDB caching
- ✅ Real-Time Ready - Seamless WebSocket integration
- ✅ Secure - AES & RSA encryption support for sensitive data
- ✅ Scalable - ComponentStore-based architecture
- ✅ Flexible - Works with Observables or Signals
🚀 Advanced Features
| Feature | Description | Learn More |
|---------|-------------|------------|
| 🔐 Enterprise Encryption | AES symmetric + RSA asymmetric encryption | Encryption Utils |
| 📡 Streaming Support | NDJSON & Server-Sent Events (SSE) | HTTP Manager |
| 📄 File Downloads | Progress tracking for large files | HTTP Manager |
| 📤 File Uploads | Multi-file upload with progress, validation, and form-data config | Upload Request |
| 📊 Pagination | Built-in pagination with page tracking | HTTP State Manager |
| 🔔 Smart Notifications | Persistent notifications with DB storage | WebSocket Guide |
| 👥 Presence Tracking | Real-time user presence by channel | WebSocket Guide |
| 🔄 Message Replay | Automatic message history on reconnect | WebSocket Guide and Message Tracker |
| 🏷️ Channel Architecture | SYS-, PUB-, MES- channel prefixes | WebSocket Guide |
| 🔌 Singleton WebSocket | Single connection across ALL instances | WebSocket Guide |
| ✨ Unified Message Service | Type-safe WebSocket messaging with auto prefixes | WebSocket Message Service |
| 🚀 Batch Requests | Execute multiple HTTP requests with sequential/parallel modes | Batch Request Guide |
| 📝 Message Tracking | Guaranteed delivery with gap detection | Message Tracker |
| 🔍 Debug Logging | Context-aware logging with dev/prod modes | Logger Service |
📋 Table of Contents
- Quick Start
- Configuration
- Services Overview
- Documentation Paths
- Architecture
- Interceptors
- Advanced Features
- Batch Requests
- Detailed Documentation
- Demo Examples
- Migration Guide
🚀 Quick Start
Installation & Setup (2 minutes)
1. Import Module
// app.module.ts
import { HttpRequestManagerModule } from 'http-request-manager';
@NgModule({
imports: [
HttpRequestManagerModule.forRoot({
httpRequestOptions: {
server: 'http://localhost:8080', // Your API base URL
retry: { times: 3, delay: 2 },
displayError: true
}
})
]
})
export class AppModule { }2. Provide APP_ID (if using encryption)
// app.module.ts
import { APP_ID } from '@angular/core';
@NgModule({
providers: [
{ provide: APP_ID, useValue: "your-unique-guid-here" }
]
})
export class AppModule { }Simple Examples
Basic HTTP Request
import { Component, inject } from '@angular/core';
import { HTTPManagerService, ApiRequest } from 'http-request-manager';
@Component({
selector: 'app-users',
template: `
<div *ngIf="isLoading$ | async">Loading...</div>
<div *ngIf="error$ | async as error" class="error">
Error: {{ error.message }}
</div>
<div *ngFor="let user of data$ | async">
{{ user.name }}
</div>
`
})
export class UsersComponent {
httpManager = inject(HTTPManagerService);
data$ = this.httpManager.data$;
isLoading$ = this.httpManager.isPending$;
error$ = this.httpManager.error$;
ngOnInit() {
this.httpManager.getRequest(
ApiRequest.adapt({ path: ['users'], displaySuccess: true, successMessage: 'Loaded users!' })
).subscribe();
}
}State Management with CRUD
@Injectable({ providedIn: 'root' })
export class UsersStore extends HTTPManagerStateService<User> {
constructor() {
super(
ApiRequest.adapt({
server: 'http://localhost:8080',
path: ['users']
}),
DataType.ARRAY
);
}
// Public API
loadUsers() { this.fetchRecords(); }
addUser(user: User) { this.createRecord(user); }
updateUser(user: User) { this.updateRecord(user); }
deleteUser(id: number) { this.deleteRecord(id); }
}
// Component
@Component({
selector: 'app-users',
template: `
<button (click)="store.loadUsers()">Load</button>
<div *ngFor="let user of store.data$ | async">
{{ user.name }}
<button (click)="store.deleteUser(user.id)">Delete</button>
</div>
`
})
export class UsersComponent {
store = inject(UsersStore);
}Request Tracking Options (Database Mode)
HTTPManagerStateService supports request tracking options for fetchRecords and fetchStream when database caching is configured (DatabaseStorage provided in the service constructor).
service.fetchRecords(RequestOptions.adapt({
path: ['ai/pagination?page=0&size=25'],
watchParams: ['page', 'size'],
watchExpiresAt: '10s'
}));Supported request options:
watchParams: Query keys you want to track for request-change behavior.watchExpiresAt: Expiry window for tracked values (examples:10s,5mn,1h).watchParamExpiry/watchParamsExpire: Alias naming used in demos/legacy wiring; map to the same expiry behavior.
Behavior notes:
- Database enabled (
DatabaseStorageconfigured): tracker is active, repeated identical query values are blocked until expiry, then can call API again. - Database disabled: tracker is bypassed; requests call the API directly each time.
forceRefresh: truealways forces an API call.
⚙️ Configuration
Module Initialization (forRoot)
Configure the library globally using the forRoot method:
import { HttpRequestManagerModule } from 'http-request-manager';
@NgModule({
imports: [
HttpRequestManagerModule.forRoot({
httpRequestOptions: {
server: 'https://api.example.com',
headers: { 'Authorization': 'Bearer token' },
retry: { times: 3, delay: 2 },
displayError: true
},
LocalStorageOptions: {
storageName: 'my-app-data',
storageSettingsName: 'my-app-settings',
options: {
encrypted: true,
expiresIn: '7d'
}
}
})
]
})
export class AppModule { }Configuration Options
HTTP Options (ConfigHTTPOptions)
| Option | Type | Description | Default |
|--------|------|-------------|---------|
| server | string | Base URL for API requests | '' |
| path | any[] | Default path segments | [] |
| headers | any | Default headers | {} |
| polling | number | Default polling interval (seconds) | 0 |
| retry | RetryOptions | Default retry configuration | { times: 0, delay: 3 } |
| stream | boolean | Enable streaming by default | false |
| displayError | boolean | Show toast errors by default | false |
| displaySuccess | boolean | Show toast on success by default | false |
| successMessage | string | Custom success toast message (optional) | undefined |
| errorMessage | string | Custom error toast message (optional, overrides default) | undefined |
Local Storage Options (LocalStorageOptions)
| Option | Type | Description | Default |
|--------|------|-------------|---------|
| storageName | string | Key for storing data | 'storage' |
| storageSettingsName | string | Key for settings metadata | 'global-storage' |
| options | SettingOptions | Default storage settings | { storage: StorageType.GLOBAL, expires: 0, expiresIn: '', encrypted: false } |
Retry Options (RetryOptions)
| Option | Type | Description | Default |
|--------|------|-------------|---------|
| times | number | Number of retry attempts | 0 |
| delay | number | Delay between retries (seconds) | 3 |
📚 Services Overview
Angular 14-18: Observable + NgRx Services
| Service | Description | Use Case |
|---------|-------------|----------|
| HTTPManagerService | Observable-based HTTP client with retry, polling, streaming | Simple API calls with loading states |
| HTTPManagerStateService | ComponentStore + HTTP + WebSocket + IndexedDB | CRUD with auto state sync and real-time updates |
| StoreStateManagerService | Persistent ComponentStore with localStorage sync | Application state persistence |
| WebSocketManagerService | Singleton WebSocket connection manager | Real-time messaging and notifications |
| WebSocketMessageService | Unified type-safe message sending service | Simplified WebSocket messaging with auto prefixes |
| MessageTrackerService | Guaranteed message delivery with gap detection | Message tracking and reconnection sync |
| LocalStorageManagerService | Secure local/session storage with encryption | User preferences and session data |
| DatabaseManagerService | IndexedDB wrapper via Dexie.js | Offline-first data access |
Angular 19+: Signal-Based Services
| Service | Description | Use Case |
|---------|-------------|----------|
| HTTPManagerSignalsService | Signal-based HTTP client for modern reactive UI | Modern Angular with Signals |
| LocalStorageSignalsManagerService | Signal-based local/session storage | Reactive persisted UI state |
| StoreStateManagerSignalsService | Signal-based persistent state service | App state persistence with computed derivations |
| WebSocketSignalsManagerService | Signal-based WebSocket manager | Signal-driven real-time dashboards and messaging |
| MessageTrackerSignalsService | Signal-based channel/message tracking | Presence, counters, last-message views |
Shared Utilities
| Service | Description | Use Case |
|---------|-------------|----------|
| UtilsService | Utilities: encryption, headers, merging, path/query | Helper functions |
Common Use Cases
| Use Case | Service to Use | Key Features |
|----------|---------------|--------------|
| Simple API calls | HTTPManagerService | Observables, retry, polling |
| Modern reactive UI | HTTPManagerSignalsService | Angular Signals |
| CRUD operations | HTTPManagerStateService | Auto state updates, pagination |
| Real-time chat | HTTPManagerStateService + WebSocket | PUB- messaging channels |
| Persistent notifications | HTTPManagerStateService + WebSocket | MES- channels with DB storage |
| State synchronization | HTTPManagerStateService + WebSocket | SYS- private channels |
| Unified WebSocket messaging | WebSocketMessageService | Type-safe, auto prefixes, validation |
| User preferences | LocalStorageManagerService | Encryption, expiration |
| Offline-first | DatabaseManagerService | IndexedDB caching, querying |
| Large local datasets | DatabaseManagerService | Bulk operations, indexing |
| Secure data storage | LocalStorageManagerService | AES encryption |
| File transfers | HTTPManagerService | Download progress tracking |
| Live data streams | HTTPManagerService | NDJSON, SSE streaming |
📖 Documentation Paths
All detailed service guides live in src/docs/. Use this README as the entry point, then choose the track that matches the Angular version in your app.
Angular 14-18: Observable + NgRx Track
| Category | Documentation | |----------|---------------| | HTTP | HTTP Manager | | State | HTTP State Manager and Store State Manager | | Real-Time | WebSocket Manager, WebSocket Message Service, and Message Tracker | | Persistence | Local Storage and Database | | Utilities | Utils, Encryption, Logger | | Reference | Models, Complete API Reference |
Angular 19+: Signal Track
| Category | Documentation | |----------|---------------| | Overview | Signal Services Overview | | HTTP | HTTP Manager Signals | | State | Store State Signals | | Real-Time | WebSocket Signals and Message Tracker Signals | | Persistence | Local Storage Signals |
🏗️ Architecture
For detailed system architecture, data flows, and design patterns, see:
System Overview
┌─────────────────────────────────────────────────────────────────┐
│ Angular Application │
├─────────────────────────────────────────────────────────────────┤
│ ┌────────────────┐ ┌────────────────┐ ┌──────────────────┐ │
│ │ Components │ │ Components │ │ Components │ │
│ │ (Signals) │ │ (Observables) │ │ (State Store) │ │
│ └───────┬────────┘ └───────┬────────┘ └────────┬─────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │HTTPManager │ │HTTPManager │ │HTTPManager │ │
│ │SignalsService│ │Service │ │StateService │ │
│ └──────┬───────┘ └──────┬───────┘ └────────┬─────────┘ │
│ │ │ │ │
│ └───────────────────┴──────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ HttpClient │ │
│ │ (Angular) │ │
│ └────────┬────────┘ │
│ │ │
├─────────────────────────────┼───────────────────────────────────┤
│ │ │
│ ┌──────────────────────────┼──────────────────────┐ │
│ │ Storage Layer │ │
│ ├──────────────────────────┼──────────────────────┤ │
│ │ ┌────────────────┐ │ ┌─────────────┐ │ │
│ │ │LocalStorage │ │ │IndexedDB │ │ │
│ │ │Manager Service │ │ │(Dexie.js) │ │ │
│ │ └────────────────┘ │ └─────────────┘ │ │
│ └──────────────────────────┼──────────────────────┘ │
│ │ │
│ ┌──────────────────────────┼──────────────────────┐ │
│ │ WebSocket Layer │ │
│ ├──────────────────────────┼──────────────────────┤ │
│ │ ┌─────────────────────────────────────┐ │ │
│ │ │ WebsocketService │ │ │
│ │ └─────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘🔧 Interceptors
The library provides several HTTP interceptors that are automatically configured:
Available Interceptors
| Interceptor | Purpose | Automatically Applied |
|-------------|---------|----------------------|
| RequestErrorInterceptor | Handles 400/500 errors with toast notifications | ✅ Yes |
| RequestHeadersInterceptor | Adds Content-Type, Accept-Language, Current-Date | ✅ Yes |
| CredentialsInterceptor | Adds withCredentials: true for CORS | ✅ Yes |
| ProxyDebuggerInterceptor | Debug logging for development | ⚙️ Configurable |
Manual Configuration
// app.module.ts
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: WithCredentialsInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: RequestHeadersInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: RequestErrorInterceptor, multi: true }
]Customization
Error handling can be customized with ErrorSettings:
import { ErrorSettings } from 'http-request-manager';
const customSettings: ErrorSettings = {
displayError: true,
displayWarning: true,
customHandler: (error) => {
// Custom error handling logic
}
};📚 Detailed Documentation
For in-depth documentation on each service and component, refer to the following detailed guides:
Detailed Docs for Angular 14-18
| Documentation | Description | |---------------|-------------| | 📖 HTTP Manager Service | Observable-based HTTP client with retry, polling, streaming, and error handling | | 📖 HTTP Manager State Service | ComponentStore integration with automatic CRUD state updates and WebSocket sync | | 📖 Store State Manager Service | Persistent ComponentStore synchronized with local/session storage | | 📖 WebSocket Manager Service | WebSocket connection management with channel-based messaging and notifications | | 📖 WebSocket Message Service | Type-safe WebSocket message sending with channel prefix helpers | | 📖 Message Tracker Service | Guaranteed message delivery with gap detection and reconnection sync | | 📖 Local Storage Manager Service | Secure local/session storage with encryption and expiration | | 📖 Database Manager Service | IndexedDB wrapper via Dexie.js with Observable API for offline-first apps | | 🚀 Batch Request Service | Execute multiple HTTP requests with sequential/parallel modes and configurable error handling | | 📤 Upload Request Service | Multi-file upload with progress tracking, validation, and form-data configuration | | 🔐 Encryption Utils | AES symmetric and RSA asymmetric encryption utilities | | 📝 Logger Service | Context-aware logging with automatic dev/prod mode detection | | 📚 Models Reference | Complete reference for all data models and configuration interfaces |
Detailed Docs for Angular 19+
| Documentation | Description | |---------------|-------------| | 📖 Signal Services Overview | Overview of the signal-based service set and migration guidance | | 📖 HTTP Manager Signals Service | Signal-based HTTP client for modern reactive UI with Angular Signals | | 📖 Local Storage Signals Manager Service | Signal-based persisted storage patterns | | 📖 Store State Signals Manager Service | Signal-based state persistence and computed state | | 📖 WebSocket Signals Manager Service | Signal-driven WebSocket connection and subscription management | | 📖 Message Tracker Signals Service | Signal-based message counting, presence, and channel metadata | | 🚀 Batch Request Service | Execute multiple HTTP requests with sequential/parallel modes and configurable error handling |
Shared Services
| Documentation | Description | |---------------|-------------| | 📖 Utils Service | Utility functions for JSON handling, encryption, headers, and validation |
Core Components
| Documentation | Description | |---------------|-------------| | 🏗️ Architecture | System architecture, data flows, and design patterns | | 🔧 Interceptors | HTTP interceptors for error handling, headers, authentication, and debugging |
Additional Resources
- Request Manager Services - Detailed API documentation for the request manager services (
src/lib/services/request-manager-services/README.md) - Encryption Utils - Encryption utility documentation (
src/lib/services/utils/encryption/README.md)
🎮 Demo Examples
Comprehensive demo components showcase all library features in action:
Available Demos
Located in src/lib/http-request-services-demo/:
| Demo Component | Features Demonstrated | |----------------|----------------------| | HttpRequestServicesDemoComponent | Main demo hub with service selection | | RequestManagerDemoComponent | HTTP CRUD, file downloads, streaming, polling, retry | | RequestManagerStateDemoComponent | State management, pagination, WebSocket sync, IndexedDB caching | | RequestManagerWsDemoComponent | Real-time chat, AI messaging, notifications, presence tracking | | LocalStorageDemoComponent | Encrypted storage, expiration, reactive signals | | LocalStorageSignalsDemoComponent | Signal-based localStorage API | | DatabaseDataDemoComponent | IndexedDB CRUD, querying, bulk operations | | RequestSignalsManagerDemoComponent | Signal-based HTTP with file downloads | | StoreStateManagerDemoComponent | Persistent state with localStorage sync |
Demo Features
HTTP Service Demos:
- ✅ Basic CRUD operations
- ✅ File download with progress tracking
- ✅ Streaming responses (NDJSON, SSE)
- ✅ Polling with countdown timers
- ✅ Retry logic with custom delays
- ✅ Error handling with toast notifications
State Management Demos:
- ✅ ComponentStore integration
- ✅ Automatic state updates
- ✅ Pagination controls
- ✅ WebSocket real-time sync
- ✅ IndexedDB caching
- ✅ Database clear/refresh
WebSocket Demos:
- ✅ Channel-based messaging (PUB- channels)
- ✅ Private state sync (SYS- channels)
- ✅ Persistent notifications (MES- channels)
- ✅ User presence tracking
- ✅ Message history & replay
- ✅ AI chat integration
- ✅ Multi-room support
Storage Demos:
- ✅ Encrypted localStorage
- ✅ SessionStorage usage
- ✅ Expiration management
- ✅ Signal-based API
- ✅ Reactive updates
Usage
<app-http-request-services-demo
[server]="'http://localhost:8080'"
[wsServer]="'ws://localhost:8080'"
[jwtToken]="'your-jwt-token'"
[adapter]="myAdapterFunction"
[mapper]="myMapperFunction">
</app-http-request-services-demo>Sample Models
Demo includes production-ready sample models:
User- User data structuresClientInfo- Client detailsSessionData- Session managementAIMessage- AI chat messagesNotification- Notification structures
📖 Migration Guide
From HttpClient to HTTPManagerService
Before:
http.get('api/users').subscribe(users => {
this.users = users;
this.loading = false;
});After:
httpManager.getRequest(
ApiRequest.adapt({ path: ['users'] })
).subscribe();
data$ = this.httpManager.data$;
isLoading$ = this.httpManager.isPending$;From Manual State to HTTPManagerStateService
Before:
users: User[] = [];
loading = false;
loadUsers() {
this.loading = true;
this.http.get('api/users').subscribe(users => {
this.users = users;
this.loading = false;
});
}
addUser(user: User) {
this.http.post('api/users', user).subscribe(newUser => {
this.users = [...this.users, newUser];
});
}After:
@Injectable()
export class UsersStore extends HTTPManagerStateService<User> {
constructor() {
super(ApiRequest.adapt({ path: ['users'] }), DataType.ARRAY);
}
loadUsers() { this.fetchRecords(); }
addUser(user: User) { this.createRecord(user); }
}
// Component
data$ = this.usersStore.data$;
isLoading$ = this.usersStore.isPending$;📋 API Reference
Core Models
All models follow the <Name>Interface + <Name>Model pattern with static adapt() methods.
| Model | Description | Documentation |
|-------|-------------|---------------|
| ApiRequest | HTTP request configuration | Models Guide |
| RetryOptions | Retry behavior settings | Models Guide |
| DataType | Data structure type (ARRAY, OBJECT) | Models Guide |
| DatabaseStorage | IndexedDB configuration | Models Guide |
| SettingOptions | Storage settings | Models Guide |
| WSOptions | WebSocket configuration | Models Guide |
| ConfigOptions | Global library configuration | Models Guide |
| StateStorageOptions | Persistent state configuration | Models Guide |
| TableSchemaDef | Database table schema | Models Guide |
| ChannelMessage | WebSocket message structure | Models Guide |
| WSUser | WebSocket user info | Models Guide |
Enums
| Enum | Values | Description |
|------|--------|-------------|
| DataType | ARRAY, OBJECT | Response data structure |
| StreamType | NDJSON, SSE | Streaming response types |
| StorageType | GLOBAL, SESSION | Storage scope |
| CommunicationType | subscribe, unsubscribe, message, notification, etc. | WebSocket message types |
| ChannelType | SYS, PUB, MES | Channel prefixes |
| ToastColors | SUCCESS, WARN, ERROR, INFO | Toast notification colors |
Configuration Tokens
| Token | Type | Purpose |
|-------|------|---------|
| CONFIG_SETTINGS_TOKEN | ConfigOptions | Global library configuration |
| APP_ID | string | Application ID for encryption |
Complete API Documentation
For comprehensive API reference with all methods, parameters, and examples: 📋 Complete API Reference
🤝 Contributing
This library is designed to be enterprise-ready and production-safe. All features include comprehensive error handling, TypeScript support, and extensive configuration options.
📄 License
This project is part of the Angular application library suite.
Need help? Check out the detailed documentation for each service, explore the demo examples, or review the architecture documentation for implementation guidance.
