http-request-manager
v18.7.31
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.
🚀 Features
Core Capabilities
| Feature | Description | Service |
|---------|-------------|---------|
| 🌐 HTTP Request Management | Observable-based & Signal-based HTTP services with retry logic, polling, and streaming | HTTPManagerService |
| 🔄 State Management | ComponentStore integration with automatic CRUD state updates | HTTPManagerStateService |
| 💬 Real-Time Communication | WebSocket messaging with channel-based architecture | WebSocketService |
| 💾 Data Persistence | LocalStorage/SessionStorage with encryption & IndexedDB caching | LocalStorageManagerService |
| 🗄️ Database Management | IndexedDB integration via Dexie.js with Observable API | DatabaseManagerService |
| ⚡ Utility Functions | JSON handling, encryption, headers, and validation | UtilsService |
Key Benefits
- ✅ Type-Safe - Full TypeScript support with generics
- ✅ Offline-First - Built-in IndexedDB caching
- ✅ Real-Time Ready - Seamless WebSocket integration
- ✅ Secure - Encryption support for sensitive data
- ✅ Scalable - ComponentStore-based architecture
- ✅ Flexible - Works with Observables or Signals
📋 Table of Contents
- Quick Start
- Configuration
- Services Overview
- Architecture
- Interceptors
- 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 *ngFor="let user of data$ | async">
{{ user.name }}
</div>
`
})
export class UsersComponent {
httpManager = inject(HTTPManagerService);
data$ = this.httpManager.data$;
isLoading$ = this.httpManager.isPending$;
ngOnInit() {
this.httpManager.getRequest(
ApiRequest.adapt({ path: ['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);
}⚙️ 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 |
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
| Service | Description | Use Case |
|---------|-------------|----------|
| HTTPManagerService | Observable-based HTTP client | Simple API calls with loading states |
| HTTPManagerSignalsService | Signal-based HTTP client | Modern reactive UI with Angular Signals |
| HTTPManagerStateService | ComponentStore with HTTP & WebSocket | CRUD operations with auto state sync |
| WebSocketService | WebSocket connection management | Real-time messaging and notifications |
| LocalStorageManagerService | Secure local storage | User preferences, session data |
| DatabaseManagerService | IndexedDB wrapper | Offline-first data access |
| StoreStateManagerService | Persistent ComponentStore | Application state persistence |
| UtilsService | Utility functions | JSON handling, encryption, headers, and conversions |
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 |
| Real-time chat | HTTPManagerStateService + WebSocket | Messaging channels |
| Persistent notifications | HTTPManagerStateService + WebSocket | Database-backed |
| User preferences | LocalStorageManagerService | Encryption, expiration |
| Offline-first | DatabaseManagerService | IndexedDB |
| Large local datasets | DatabaseManagerService | Querying, indexing |
🏗️ 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
- RequestErrorInterceptor - Handles 400/500 errors with toast notifications
- WithCredentialsInterceptor - Adds
withCredentials: trueto requests - RequestHeadersInterceptor - Adds common headers (Content-Type, Accept-Language, Current-Date)
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 }
]📚 Detailed Documentation
For in-depth documentation on each service and component, refer to the following detailed guides:
Services
| Documentation | Description | |---------------|-------------| | 📖 HTTP Manager Service | Observable-based HTTP client with retry, polling, streaming, and error handling | | 📖 HTTP Manager Signals Service | Signal-based HTTP client for modern reactive UI with Angular Signals | | 📖 HTTP Manager State Service | ComponentStore integration with automatic CRUD state updates and WebSocket sync | | 📖 WebSocket Manager Service | WebSocket connection management with channel-based messaging and notifications | | 📖 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 | | 📖 Store State Manager Service | Persistent ComponentStore synchronized with local/session storage | | 📖 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:
Available Demos
- HttpRequestServicesDemoComponent - Main demo component
- RequestManagerDemoComponent - HTTP service demonstrations
- RequestManagerStateDemoComponent - State management examples
- RequestManagerWsDemoComponent - WebSocket functionality
- LocalStorageDemoComponent - Local storage examples
- DatabaseDataDemoComponent - IndexedDB operations
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>📖 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
- ApiRequest - HTTP request configuration
- RetryOptions - Retry behavior settings
- DataType - Data structure type (ARRAY, OBJECT)
- DatabaseStorage - IndexedDB configuration
- SettingOptions - Storage settings
- WSOptions - WebSocket configuration
Enums
- StreamType - Streaming response types
- StorageType - Storage scope (GLOBAL, SESSION)
- CommunicationType - WebSocket message types
🤝 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.
