Module which has common services, pipes, directives and interfaces which can be used on all projects.
Wacom is SSR-safe and works with Angular Universal: browser-only APIs are guarded, and features that require a browser runtime activate only on the client.
$ npm i --save wacomimport { provideWacom } from 'wacom';
export const appConfig = {
providers: [provideWacom()],
};WacomModule is still available for older applications but will be deprecated in future versions. Use provideWacom to configure the library when working with standalone APIs.
You can pass an optional configuration object to provideWacom to override the library defaults.
import { provideWacom } from 'wacom';
export const appConfig = {
providers: [
provideWacom({
http: { url: 'https://api.example.com' },
store: { prefix: 'waStore' },
meta: {
useTitleSuffix: false,
defaults: { links: {} },
},
network: {},
// enable and configure sockets if needed
socket: false,
io: undefined,
}),
],
};| Name | Description |
|---|---|
Core |
Common supportive function which can be used in any service |
Emitter |
Lightweight app-wide event and task signaling |
Http |
Http layer for HttpClient |
Store |
Service responsible for keeping information on the device |
Meta |
Website meta tags management within router |
Crud |
Provides basic CRUD operations for managing data with HTTP services |
Socket |
Manages WebSocket connections and real-time data communication |
Time |
Provides utilities for date and time manipulation and formatting |
Dom |
Facilitates DOM manipulation and dynamic component loading |
Network |
Monitors network connectivity and latency |
RTC |
Wraps WebRTC peer connections and local media streams |
Util |
Utility methods for forms, validation, and CSS variables |
Theme |
Manages UI theme mode, density, and radius preferences |
Translate |
Lightweight, signal-based runtime translate engine |
The CoreService manages the initialization of various platform-specific services depending on whether the application is running on the server or the client.
ssr(boolean): Indicates whether the application is running on the server side.localStorage(any): Local storage object. Uses a mock object on the server side.navigator(any): Navigator object. Uses a mock object on the server side.document(any): Document object. Uses a mock object on the server side.window(any): Window object. Uses a mock object on the server side.
The CoreService extends the String prototype with a capitalize method, allowing you to capitalize the first letter of any string instance.
Capitalizes the first letter of the string and makes the rest of the string lowercase.
- Example: const exampleString = "hellO"; console.log(exampleString.capitalize()); // Output: "Hello"
The CoreService provides an ota method to convert an object to an array. Optionally, it can hold keys instead of values.
Converts an object to an array. Optionally holds keys instead of values.
-
Parameters:
obj(any): The object to be converted.holder(boolean): If true, the keys will be held in the array; otherwise, the values will be held. Default isfalse.
-
Returns:
any[]: The resulting array.
-
Example:
const exampleObj = { a: 1, b: 2, c: 3 };
const resultValues = coreService.ota(exampleObj);
console.log(resultValues); // Output: [1, 2, 3]
const resultKeys = coreService.ota(exampleObj, true);
console.log(resultKeys); // Output: ['a', 'b', 'c']The CoreService provides a splice method to remove elements from one array that are present in another array based on a comparison field.
Removes elements from fromArray that are present in removeArray based on a comparison field.
-
Parameters:
removeArray(any[]): The array of elements to remove.fromArray(any[]): The array from which to remove elements.compareField(string): The field to use for comparison. Default is_id.
-
Returns:
any[]: The modifiedfromArraywith elements removed.
-
Example:
const removeArray = [{ _id: '1' }, { _id: '3' }];
const fromArray = [{ _id: '1' }, { _id: '2' }, { _id: '3' }, { _id: '4' }];
const result = coreService.splice(removeArray, fromArray);
console.log(result); // Output: [{ _id: '2' }, { _id: '4' }]
The CoreService provides an ids2id method to unite multiple _id values into a single unique _id. The resulting _id is unique regardless of the order of the input _id values.
Unites multiple _id values into a single unique _id. The resulting _id is unique regardless of the order of the input _id values.
-
Parameters:
...args(string[]): The _id values to be united.
-
Returns:
string: The unique combined _id.
-
Example:
const id1 = "20230101abc";
const id2 = "20230102xyz";
const id3 = "20230101def";
const result = coreService.ids2id(id1, id2, id3);
console.log(result); // Output will be the ids sorted by the first 8 characters and joinedThe CoreService provides an afterWhile method to delay the execution of a callback function for a specified amount of time. If called again within that time, the timer resets.
Delays the execution of a callback function for a specified amount of time. If called again within that time, the timer resets.
-
Parameters:
doc(string | object | (() => void)): A unique identifier for the timer, an object to host the timer, or the callback function.cb(() => void): The callback function to execute after the delay.time(number): The delay time in milliseconds. Default is 1000.
-
Example:
coreService.afterWhile('example', () => {
console.log('This message is delayed by 1 second');
}, 1000);
const obj = {};
coreService.afterWhile(obj, () => {
console.log('This message is delayed by 1 second and stored in obj.__afterWhile');
}, 1000);
coreService.afterWhile(() => {
console.log('This message is delayed by 1 second using the default doc "common"');
}, 1000);The CoreService provides a copy method to recursively copy properties from one object to another.
Recursively copies properties from one object to another.
-
Parameters:
from: The source object from which properties are copied.to: The target object to which properties are copied.
-
Example:
const source = { a: 1, b: { c: 2 } };
const target = {};
coreService.copy(source, target);
console.log(target); // Output: { a: 1, b: { c: 2 } }The CoreService provides methods to detect the client's device type (mobile, tablet, or web).
device(string): The detected device type.
Detects the device type based on the user agent.
- Example:
coreService.detectDevice();Checks if the device is a mobile device.
-
Returns:
boolean: Returns true if the device is a mobile device.
-
Example:
console.log(coreService.isMobile()); // Output: true or falseChecks if the device is a tablet.
-
Returns:
boolean: Returns true if the device is a tablet.
-
Example:
console.log(coreService.isTablet()); // Output: true or falseChecks if the device is a web browser.
-
Returns:
boolean: Returns true if the device is a web browser.
-
Example:
console.log(coreService.isWeb()); // Output: true or falseChecks if the device is an Android device.
-
Returns:
boolean: Returns true if the device is an Android device.
-
Example:
console.log(coreService.isAndroid()); // Output: true or falseChecks if the device is an iOS device.
-
Returns:
boolean: Returns true if the device is an iOS device.
-
Example:
console.log(coreService.isIos()); // Output: true or falseThe CoreService provides methods for managing the application's version. The version is dynamically constructed from the app version and the date version.
version(string): The combined version string of the application.appVersion(string): The application version.dateVersion(string): The date version.
Sets the combined version string based on appVersion and dateVersion.
- Example:
coreService.setVersion();Sets the app version and updates the combined version string.
-
Parameters:
appVersion(string): The application version to set.
-
Example:
coreService.setAppVersion('1.2.3');Sets the date version and updates the combined version string.
-
Parameters:
dateVersion(string): The date version to set.
-
Example:
coreService.setDateVersion('2023-01-01');The CoreService provides methods for managing locks on resources to prevent concurrent access. This is useful in scenarios where you need to ensure that only one part of your application is accessing or modifying a resource at any given time.
Locks a resource to prevent concurrent access.
-
Parameters:
which(string): The resource to lock, identified by a string.
-
Example: coreService.lock('myResource');
Unlocks a resource, allowing other processes or threads to access it.
-
Parameters:
which(string): The resource to unlock, identified by a string.
-
Example: coreService.unlock('myResource');
Returns a Promise that resolves when the specified resource is unlocked. This is useful for waiting until a resource becomes available.
-
Parameters:
which(string): The resource to watch for unlocking, identified by a string.
-
Returns:
Promise<void>: A Promise that resolves when the resource is unlocked.
-
Example: coreService.onUnlock('myResource').then(() => { console.log('Resource is now unlocked'); });
Checks if a resource is currently locked.
-
Parameters:
which(string): The resource to check, identified by a string.
-
Returns:
boolean: True if the resource is locked, false otherwise.
-
Example: if (coreService.locked('myResource')) { console.log('Resource is currently locked'); } else { console.log('Resource is available'); }
Here's an example demonstrating how to use the locking management methods in CoreService:
import { CoreService } from 'wacom';
export class AppComponent {
constructor(private coreService: CoreService) {
this.manageResource();
}
async manageResource() {
this.coreService.lock('resource1');
console.log('Resource locked');
setTimeout(() => {
this.coreService.unlock('resource1');
console.log('Resource unlocked');
}, 2000);
await this.coreService.onUnlock('resource1');
console.log('Resource is now available for use');
}
}In this example:
- The
lockmethod is used to lock a resource identified by'resource1'. - The
unlockmethod is called after a timeout to unlock the resource. - The
onUnlockmethod returns a Promise that resolves when the resource is unlocked, allowing the code to wait until the resource is available again.
This ensures controlled access to the resource, preventing race conditions and ensuring data integrity.
The EmitterService provides a lightweight event bus and completion signaling built on Angular Signals and RxJS.
emit(id: string, data?: any): void: Publish an event on a channel.on<T = any>(id: string): Observable<T>: Subscribe to a channel (hot, no replay).off(id: string): void: Close and remove a channel.offAll(): void: Close and remove all channels.has(id: string): boolean: Check if a channel exists.
Example:
import { EmitterService } from 'wacom';
constructor(private emitter: EmitterService) {}
ngOnInit() {
this.emitter.on<string>('user:login').subscribe((uid) => {
console.log('Logged in:', uid);
});
}
login(uid: string) {
this.emitter.emit('user:login', uid);
}Track once-off tasks and await their completion.
complete<T = any>(task: string, value: T = true): void: Mark task done with payload.clearCompleted(task: string): void: Reset completion state.completed(task: string): any | undefined: Read current payload orundefined.isCompleted(task: string): boolean: Convenience check.onComplete(tasks: string | string[], opts?: { mode?: 'all' | 'any'; timeoutMs?: number; abort?: AbortSignal; }): Observable<any | any[]>: Await task(s) completion.
Example:
// Somewhere that waits for a single task
this.emitter.onComplete('profile:loaded').subscribe(() => {
// safe to render UI
});
// Somewhere that fulfills it
await api.loadProfile();
this.emitter.complete('profile:loaded');
// Wait for any of several tasks
this.emitter
.onComplete(['a', 'b'], { mode: 'any', timeoutMs: 5000 })
.subscribe(which => console.log('First done:', which));The HttpService provides an HTTP layer for HttpClient in Angular, supporting both callbacks and observables for various HTTP operations.
Sets the base URL for HTTP requests. Parameters:
url(string): The base URL.
Example:
httpService.setUrl('https://api.example.com');Removes the base URL for HTTP requests. Example:
httpService.removeUrl();Sets a header for HTTP requests. Parameters:
key(string): The header key.value(string): The header value.
Example:
httpService.set('Authorization', 'Bearer token');Gets the value of a specified header. Parameters:
key(string): The header key.
Returns:
- The header value.
Example:
const authHeader = httpService.header('Authorization');Removes a specified header. Parameters:
key(string): The header key.
Example:
httpService.remove('Authorization');Performs a POST request. Parameters:
url(string): The URL for the request.doc(any): The request body.callback(function): The callback function.opts(any): Additional options.
Returns:
- An observable for the request.
Example:
httpService.post('/endpoint', data, (resp) => {
console.log(resp);
}).subscribe();Performs a PUT request. Parameters:
url(string): The URL for the request.doc(any): The request body.callback(function): The callback function.opts(any): Additional options.
Returns:
- An observable for the request.
Example:
httpService.put('/endpoint', data, (resp) => {
console.log(resp);
}).subscribe();Performs a PATCH request. Parameters:
url(string): The URL for the request.doc(any): The request body.callback(function): The callback function.opts(any): Additional options.
Returns:
- An observable for the request.
Example:
httpService.patch('/endpoint', data, (resp) => {
console.log(resp);
}).subscribe();Performs a DELETE request. Parameters:
url(string): The URL for the request.callback(function): The callback function.opts(any): Additional options.
Returns:
- An observable for the request.
Example:
httpService.delete('/endpoint', (resp) => {
console.log(resp);
}).subscribe();Performs a GET request. Parameters:
url(string): The URL for the request.callback(function): The callback function.opts(any): Additional options.
Returns:
- An observable for the request.
Example:
httpService.get('/endpoint', (resp) => {
console.log(resp);
}).subscribe();Clears all locked requests. Example:
httpService.clearLocked();Locks the service to prevent further requests. Example:
httpService.lock();Unlocks the service to allow requests. Example:
httpService.unlock();StoreService provides a unified, async-first API for working with storage (localStorage by default or a custom provider via config).
It supports raw values, safe JSON handling, key prefixing, and optional lifecycle hooks.
- async/await everywhere (no separate
*Asyncmethods) - optional side-effects via
options - automatic JSON corruption handling
- configurable storage backend
- prefix support for namespacing
storeService.setPrefix('app_');All keys will be stored as app_<key> (plus global config prefix if defined).
Stores a raw string value.
await storeService.set('token', 'abc123');With hooks:
await storeService.set('token', 'abc123', {
onSuccess: () => console.log('saved'),
onError: console.error,
});Returns: Promise<boolean>
Retrieves a raw string value.
const token = await storeService.get('token');With hooks:
const token = await storeService.get('token', {
onSuccess: v => console.log(v),
onError: console.error,
});Returns: Promise<string | null>
Stores a JSON-serializable value.
await storeService.setJson('profile', { name: 'Den', role: 'dev' });With hooks:
await storeService.setJson('profile', user, {
onSuccess: () => console.log('saved'),
onError: console.error,
});Returns: Promise<boolean>
Retrieves a JSON value safely.
- empty or missing →
null(ordefaultValue) - corrupted JSON → auto-cleared (by default)
const profile = await storeService.getJson<User>('profile');With defaults and error handling:
const profile = await storeService.getJson<User>('profile', {
defaultValue: {},
onError: console.warn,
});Disable auto-clean:
await storeService.getJson('profile', {
clearOnError: false,
});Returns: Promise<T | null>
Removes a single key.
await storeService.remove('token');With hooks:
await storeService.remove('token', {
onSuccess: () => console.log('removed'),
onError: console.error,
});Returns: Promise<boolean>
Clears all stored values.
await storeService.clear();With hooks:
await storeService.clear({
onSuccess: () => console.log('cleared'),
onError: console.error,
});Returns: Promise<boolean>
All methods accept an optional options parameter:
interface StoreOptions<T = unknown> {
onSuccess?: (value?: T | null) => void;
onError?: (err: unknown) => void;
defaultValue?: T; // getJson only
clearOnError?: boolean; // getJson only (default: true)
}The MetaService manages meta tags and titles in an Angular application. It allows setting defaults, updating meta tags, and configuring titles dynamically.
Sets the default meta tags, merging the provided values with any existing defaults.
Parameters:
defaults(object): The default meta tags including optionallinks.
Example:
metaService.setDefaults({ title: 'Default Title', description: 'Default Description' });
// Later calls merge with previous defaults instead of replacing them
metaService.setDefaults({ description: 'Updated Description' });Sets the title and optional title suffix, updating the title, og:title, and twitter:title meta tags.
Parameters:
title(string): The title to set.titleSuffix(string): The title suffix to append.
Returns:
MetaService: The MetaService instance.
Example:
metaService.setTitle('My Page Title', ' | My Website');Sets link tags.
Parameters:
links(object): The links to set.
Returns:
MetaService: The MetaService instance.
Example:
metaService.setLink({ canonical: 'https://example.com', stylesheet: 'https://example.com/style.css' });Sets a meta tag.
Parameters:
tag(string): The meta tag name.value(string): The meta tag value.prop(string): The meta tag property.
Returns:
MetaService: The MetaService instance.
Example:
metaService.setTag('description', 'This is a description', 'name');Removes a meta tag.
Parameters:
tag(string): The meta tag name.prop(string): The meta tag property.
Example:
metaService.removeTag('description', 'name');Updates a meta tag.
Parameters:
tag(string): The meta tag name.value(string): The meta tag value.prop(string): The meta tag property.
The UtilService manages various UI-related tasks in an Angular application, including CSS management, form validation, and generating sample data for UI components.
Manages form states.
Parameters:
id(string): The form identifier.
Returns:
any: The form state object.
Example:
const formState = utilService.form('contactForm');Validates input values based on the specified type.
Parameters:
value(any): The value to validate.kind(string): The type of validation.extra(number): Additional validation criteria.
Returns:
boolean: True if the value is valid, false otherwise.
Example:
const isValidEmail = utilService.valid('test@example.com', 'email');Determines the strength of a password.
Parameters:
value(string): The password to evaluate.
Returns:
number: The strength level of the password.
Example:
const passwordLevel = utilService.level('Password123!');Sets multiple CSS variables.
Parameters:
variables(object): The CSS variables to set.opts(any): Options for setting the variables.
Example:
utilService.set({ '--primary-color': '#ff0000' }, 'local');Retrieves the stored CSS variables.
Returns:
object: The stored CSS variables.
Example:
const cssVariables = utilService.get();Removes specified CSS variables.
Parameters:
keys(string | array): The keys of the CSS variables to remove.
Example:
utilService.remove('primary-color secondary-color');Generates an array of sample data.
Parameters:
arrLen(number): The length of the array.type(string): The type of data to generate.
Returns:
array: An array of sample data.
Example:
const sampleArray = utilService.arr(5, 'text');Generates a random text string.
Parameters:
length(number): The length of the text string.
Returns:
string: A random text string.
Example:
const randomText = utilService.text(15);The CrudService is designed to manage CRUD (Create, Read, Update, Delete) operations in an Angular application. It interacts with an API, stores documents locally, and provides methods for handling various CRUD operations. It should be extended by specific services that manage different document types.
Creates a new document with a temporary ID and status flags.
Parameters:
doc(Document, optional): A base document to initialize.
Returns:
Document: A new document instance with default properties.
Example: const newDoc = workService.new();
Retrieves a document by its ID. If the document doesn't exist, a new one is created.
Parameters:
_id(string): The document ID.
Returns:
Document: The document instance.
Example: const doc = workService.doc('12345');
Adds a new document or updates an existing document in the local store. It will attempt to update the document if it already exists in the collection.
Parameters:
doc(Document): The document to add or update.
Example: workService.addDoc(doc);
Adds multiple documents to the service. Each document will either be added or updated depending on whether it already exists.
Parameters:
docs(Document[]): The array of documents to add.
Example: workService.addDocs(docs);
Saves the current state of documents to local storage.
Example: workService.setDocs();
Retrieves the current list of documents stored locally.
Returns:
Document[]: The list of documents.
Example: const docs = workService.getDocs();
Sets the number of documents to display per page for pagination.
Parameters:
_perPage(number): The number of documents per page.
Example: workService.setPerPage(10);
Fetches a list of documents from the API with optional pagination and other settings.
Parameters:
config(object, optional): The configuration for pagination (pageandperPage).options(CrudOptions, optional): Options for callbacks and error handling.
Returns:
Observable<Document[]>: An observable of the retrieved documents.
Example: workService.get({ page: 1 }, { callback: (docs) => console.log(docs) });
Creates a new document in the API and adds it to the local store. The document is only created once.
Parameters:
doc(Document): The document to create.options(CrudOptions, optional): Options for callbacks and error handling.
Returns:
Observable<Document> | void: An observable of the created document or void if the document was already created.
Example: workService.create(newDoc, { callback: (doc) => console.log(doc) });
Fetches a document from the API based on a query object and adds it to the local store.
Parameters:
query(object, optional): The query object to filter the documents.options(CrudOptions, optional): Options for callbacks and error handling.
Returns:
Observable<Document>: An observable of the fetched document.
Example: workService.fetch({ name: 'example' }, { callback: (doc) => console.log(doc) });
Updates a document after a specified delay using a core service function to handle the delay.
Parameters:
doc(Document): The document to update.options(CrudOptions, optional): Options for callbacks and error handling.
Example: workService.updateAfterWhile(doc, { callback: (doc) => console.log(doc) });
Updates a document in the API and reflects the changes locally.
Parameters:
doc(Document): The document to update.options(CrudOptions, optional): Options for callbacks and error handling.
Returns:
Observable<Document>: An observable of the updated document.
Example: workService.update(doc, { callback: (doc) => console.log(doc) });
Unique update a document field in the API.
Parameters:
doc(Document): The document to update.options(CrudOptions, optional): Optional callback and error handling configuration.
Returns:
Observable<Document>: An observable that resolves with the updated document.
Example: workService.unique(doc, { callback: (doc) => console.log('Document updated', doc) });
Deletes a document from the API and updates the local store.
Parameters:
doc(Document): The document to delete.options(CrudOptions, optional): Options for callbacks and error handling.
Returns:
Observable<Document>: An observable of the deleted document.
Example: workService.delete(doc, { callback: (doc) => console.log(doc) });
Represents a CRUD document.
Properties:
_id(string): The document ID.__created(boolean): Indicates if the document is created.__modified(boolean): Indicates if the document is modified.
Example: interface CrudDocument { _id: string; **created: boolean; **modified: boolean; }
import { Injectable } from '@angular/core';
import { CoreService, HttpService, StoreService, CrudService, CrudDocument } from 'wacom';
export interface Work extends CrudDocument {
name: string;
description: string;
}
@Injectable({
providedIn: 'root',
})
export class WorkService extends CrudService<Work> {
works: Work[] = this.getDocs();
constructor(_http: HttpService, _store: StoreService, _core: CoreService) {
super(
{
name: 'work',
},
_http,
_store,
_core,
);
this.get();
}
}The SocketService manages WebSocket connections using socket.io. It handles setting up the connection, listening for events, and emitting messages.
Sets the URL for the WebSocket connection and reloads the socket. Parameters:
url(string): The URL of the WebSocket server.
Example:
socketService.setUrl('https://example.com');Subscribes to a WebSocket event.
Parameters:
to(string): The event to subscribe to.cb(function): The callback function to execute when the event is received.
Example:
socketService.on('message', (msg) => {
console.log('Received message:', msg);
});Emits a message to a WebSocket event.
Parameters:
to(string): The event to emit the message to.message(any): The message to emit.room(any): Optional room to emit the message to.
Example:
socketService.emit('message', { text: 'Hello, World!' });import { SocketService } from 'wacom';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor(private socketService: SocketService) {
this.socketService.setUrl('https://example.com');
this.socketService.on('connect', () => {
console.log('Connected to WebSocket');
});
this.socketService.on('message', msg => {
console.log('Received message:', msg);
});
}
sendMessage() {
this.socketService.emit('message', { text: 'Hello, World!' });
}
}The TimeService provides comprehensive date and time management, including timezone handling, formatting dates, and utility functions for calendar operations.
Returns the name of the day of the week for a given date.
Parameters:
date(Date): The date for which to get the day of the week.format('short' | 'long'): The format in which to return the day name. Default is 'long'.
Returns:
- The name of the day of the week.
Example:
const dayName = timeService.getDayName(new Date(), 'short');
console.log(dayName); // Output: 'Mon'Returns the name of the month for a given index.
Parameters:
monthIndex(number): The month index (0-11).format('short' | 'long'): The format in which to return the month name. Default is 'long'.
Returns:
- The name of the month.
Example:
const monthName = timeService.getMonthName(0, 'short');
console.log(monthName); // Output: 'Jan'Formats a date according to the specified format and timezone.
Parameters:
date(Date): The date to format.format(string): The format string (see Angular DatePipe documentation for format options).timezone(string): The timezone to use for formatting.
Returns:
- The formatted date string.
Example:
const formattedDate = timeService.formatDate(new Date(), 'fullDate', 'America/New_York');
console.log(formattedDate); // Output: 'Monday, January 1, 2023'Converts a date to a different timezone. Parameters:
date(Date): The date to convert.timezone(string): The timezone to convert to.
Returns:
- The date in the new timezone.
Example:
const dateInTimezone = timeService.convertToTimezone(new Date(), 'Asia/Tokyo');
console.log(dateInTimezone);Returns the start of the day for a given date. Parameters:
date(Date): The date for which to get the start of the day.
Returns:
- The start of the day (midnight) for the given date.
Example:
const startOfDay = timeService.startOfDay(new Date());
console.log(startOfDay); // Output: '2023-01-01T00:00:00.000Z'Returns the end of the day for a given date. Parameters:
date(Date): The date for which to get the end of the day.
Returns:
- The end of the day (one millisecond before midnight) for the given date.
Example:
const endOfDay = timeService.endOfDay(new Date());
console.log(endOfDay); // Output: '2023-01-01T23:59:59.999Z'Returns the number of days in a given month and year. Parameters:
month(number): The month (0-11).year(number): The year.
Returns:
- The number of days in the month.
Example:
const daysInMonth = timeService.getDaysInMonth(1, 2023);
console.log(daysInMonth); // Output: 28Checks if a given year is a leap year. Parameters:
year(number): The year to check.
Returns:
- True if the year is a leap year, false otherwise.
Example:
const isLeap = timeService.isLeapYear(2024);
console.log(isLeap); // Output: trueAdds a specified number of days to a date. Parameters:
date(Date): The date to which to add days.days(number): The number of days to add.
Returns:
- The new date with the added days.
Example:
const newDate = timeService.addDays(new Date(), 10);
console.log(newDate);Adds a specified number of months to a date. Parameters:
date(Date): The date to which to add months.months(number): The number of months to add.
Returns:
- The new date with the added months.
Example:
const newDate = timeService.addMonths(new Date(), 2);
console.log(newDate);Adds a specified number of years to a date. Parameters:
date(Date): The date to which to add years.years(number): The number of years to add.
Returns:
- The new date with the added years.
Example:
const newDate = timeService.addYears(new Date(), 5);
console.log(newDate);Adds a specified number of hours to a date.
Parameters:
date(Date): The date to which to add hours.hours(number): The number of hours to add.
Returns:
- The new date with the added hours.
Example:
const newDate = timeService.addHours(new Date(), 3);
console.log(newDate);Adds a specified number of minutes to a date.
Parameters:
date(Date): The date to which to add minutes.minutes(number): The number of minutes to add.
Returns:
- The new date with the added minutes.
Example:
const newDate = timeService.addMinutes(new Date(), 30);
console.log(newDate);Adds a specified number of seconds to a date.
Parameters:
date(Date): The date to which to add seconds.seconds(number): The number of seconds to add.
Returns:
- The new date with the added seconds.
Example:
const newDate = timeService.addSeconds(new Date(), 45);
console.log(newDate);Subtracts a specified number of days from a date. Parameters:
date(Date): The date from which to subtract days.days(number): The number of days to subtract.
Returns:
- The new date with the subtracted days.
Example:
const newDate = timeService.subtractDays(new Date(), 5);
console.log(newDate);Subtracts a specified number of months from a date. Parameters:
date(Date): The date from which to subtract months.months(number): The number of months to subtract.
Returns:
- The new date with the subtracted months.
Example:
const newDate = timeService.subtractMonths(new Date(), 3);
console.log(newDate);Subtracts a specified number of years from a date. Parameters:
date(Date): The date from which to subtract years.years(number): The number of years to subtract.
Returns:
- The new date with the subtracted years.
Example:
const newDate = timeService.subtractYears(new Date(), 2);
console.log(newDate);Subtracts a specified number of hours from a date.
Parameters:
date(Date): The date from which to subtract hours.hours(number): The number of hours to subtract.
Returns:
- The new date with the subtracted hours.
Example:
const newDate = timeService.subtractHours(new Date(), 4);
console.log(newDate);Subtracts a specified number of minutes from a date.
Parameters:
date(Date): The date from which to subtract minutes.minutes(number): The number of minutes to subtract.
Returns:
- The new date with the subtracted minutes.
Example:
const newDate = timeService.subtractMinutes(new Date(), 15);
console.log(newDate);Subtracts a specified number of seconds from a date.
Parameters:
date(Date): The date from which to subtract seconds.seconds(number): The number of seconds to subtract.
Returns:
- The new date with the subtracted seconds.
Example:
const newDate = timeService.subtractSeconds(new Date(), 20);
console.log(newDate);Checks if two dates are on the same day. Parameters:
date1(Date): The first date.date2(Date): The second date.
Returns:
- True if the dates are on the same day, false otherwise.
Example:
const sameDay = timeService.isSameDay(new Date(), new Date());
console.log(sameDay); // Output: trueReturns the ISO week number for a given date.
Parameters:
date(Date): The date for which to get the week number.
Returns:
- The ISO week number (1-53).
Example:
const weekNumber = timeService.getWeekNumber(new Date());
console.log(weekNumber); // Output: 35 (example)Returns the number of weeks in a month for a given month and year.
Parameters:
month(number): The month (0-11).year(number): The year.
Returns:
- The number of weeks in the month.
Example:
const weeksInMonth = timeService.getWeeksInMonth(2, 2025);
console.log(weeksInMonth); // Output: 6 (example for March 2025)The DomService facilitates DOM manipulation and dynamic component loading in Angular applications.
appendById(component: any, options: any = {}, id: string): { nativeElement: HTMLElement, componentRef: ComponentRef<any> }
Appends a component to a specified element by ID.
Parameters:
component(Type<T>): The component to append.options(Partial<T>): The options to project into the component.id(string): The ID of the element to append the component to.
Returns:
- An object containing the native element and the component reference (
ComponentRef<T>).
Example:
const result = domService.appendById(MyComponent, { inputProp: 'value' }, 'elementId');
console.log(result.nativeElement); // Output: The native DOM element
console.log(result.componentRef); // Output: The component referenceappendComponent<T>(component: Type<T>, options: Partial<T> = {}, element: HTMLElement = this.core.document.body): { nativeElement: HTMLElement, componentRef: ComponentRef<T> }
Appends a component to a specified element or to the body. Parameters:
component(Type<T>): The component to append.options(Partial<T>): The options to project into the component.element(HTMLElement): The element to append the component to. Defaults to body.
Returns:
- An object containing the native element and the component reference (
ComponentRef<T>).
Example:
const result = domService.appendComponent(MyComponent, { inputProp: 'value' });
console.log(result.nativeElement); // Output: The native DOM element
console.log(result.componentRef); // Output: The component referenceGets a reference to a dynamically created component. Parameters:
component(Type<T>): The component to create.options(Partial<T>): The options to project into the component.
Returns:
- The component reference (
ComponentRef<T>).
Example:
const componentRef = domService.getComponentRef(MyComponent, { inputProp: 'value' });
console.log(componentRef); // Output: The component referenceProjects the inputs onto the component. Parameters:
component(ComponentRef): The component reference.options(any): The options to project into the component.
Returns:
- The component reference with the projected inputs.
Example:
const componentRef = domService.getComponentRef(MyComponent);
domService.projectComponentInputs(componentRef, { inputProp: 'value' });
console.log(componentRef.instance.inputProp); // Output: 'value'import { DomService } from './dom.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private domService: DomService) {}
addComponent() {
const result = this.domService.appendById(MyComponent, { inputProp: 'value' }, 'elementId');
console.log(result.nativeElement); // Output: The native DOM element
console.log(result.componentRef); // Output: The component reference
result.remove(); // Cleanup when done
}
}The NetworkService monitors network connectivity and latency using Angular signals.
It periodically probes configurable endpoints and emits wacom_online or wacom_offline
events through the CoreService when status changes.
status(Signal<NetworkStatus>): Current connectivity classification (good,poor, ornone).latencyMs(Signal<number | null>): Measured latency to the nearest reachable endpoint.isOnline(Signal<boolean>): Indicates whether the browser reports an online state.
Performs an immediate connectivity check and updates all signals.
Example:
await networkService.recheckNow();The RtcService wraps WebRTC peer connections and local media streams.
initLocalStream(): Promise<MediaStream>– initializes and returns the local media stream.createPeer(id: string): Promise<RTCPeerConnection>– creates a peer connection and attaches local tracks.createOffer(id: string): Promise<RTCSessionDescriptionInit>– creates an SDP offer.createAnswer(id: string, offer: RTCSessionDescriptionInit): Promise<RTCSessionDescriptionInit>– responds to an offer.setRemoteAnswer(id: string, answer: RTCSessionDescriptionInit): Promise<void>– applies a remote answer.addIceCandidate(id: string, candidate: RTCIceCandidateInit): void– adds an ICE candidate.getLocalStream(): MediaStream | null– returns the initialized local stream.closePeer(id: string): void– closes a peer connection.closeAll(): void– closes all peers and stops the local stream.
Example:
import { RtcService } from 'wacom';
constructor(private rtc: RtcService) {}
async connect(id: string) {
await this.rtc.initLocalStream();
await this.rtc.createPeer(id);
const offer = await this.rtc.createOffer(id);
// send offer to remote peer...
}The ThemeService manages UI theme preferences by setting data attributes on the
document root, persisting them in localStorage, and exposing Angular signals.
mode: Signal<ThemeMode | string | undefined>- current theme mode.density: Signal<ThemeDensity | undefined>- current density.radius: Signal<ThemeRadius | undefined>- current radius.
setMode(mode: ThemeMode): void- setsdata-mode, persiststheme.mode, updatesmode.setDensity(density: ThemeDensity): void- setsdata-density, persiststheme.density, updatesdensity.setRadius(radius: ThemeRadius): void- setsdata-radius, persiststheme.radius, updatesradius.init(): void- loads preferences fromlocalStorage(or defaults tolight,comfortable,rounded) and updates signals.
import { ThemeService } from "wacom";
constructor(private theme: ThemeService) {}
ngOnInit() {
this.theme.init();
this.theme.setMode("dark");
this.theme.setDensity("compact");
this.theme.setRadius("square");
}Wacom includes a lightweight, signal-based runtime translation engine built for Angular Signals.
It provides:
- reactive translations via
WritableSignal<string> - zero-config fallback (source text renders until translated)
- config-based bootstrap via
provideTranslate(...) - inline dictionaries or lazy JSON loading per language
- optional language persistence (stored separately)
- directive + pipe for ergonomic template usage
- instant language switching without reload
Unlike compile-time Angular i18n, this works fully at runtime.
export interface Translate {
sourceText: string;
text: string;
}Each sourceText acts as both:
- translation key
- default visible UI text (fallback)
import { provideTranslate } from 'wacom';
providers: [
provideTranslate({
defaultLanguage: 'en',
language: 'en',
}),
];language ?? defaultLanguage is used for initial startup language.
import { provideTranslate } from 'wacom';
providers: [
provideTranslate({
defaultLanguage: 'en',
language: 'en',
translations: {
en: [
{ sourceText: 'Hello', text: 'Hello' },
{ sourceText: 'Save', text: 'Save' },
],
de: [
{ sourceText: 'Hello', text: 'Hallo' },
{ sourceText: 'Save', text: 'Speichern' },
],
},
}),
];import { provideTranslate } from 'wacom';
providers: [
provideTranslate({
defaultLanguage: 'en',
language: 'en',
folder: '/i18n/',
}),
];With folder: '/i18n/' and language: 'en', runtime URL is:
/i18n/en.json
File format:
{
"Hello": "Hallo",
"Save": "Speichern"
}import { TranslateService } from "wacom";
private _translateService = inject(TranslateService);
title = this._translateService.translate("Create project");The returned value is a WritableSignal<string>.
If no translation exists yet, it renders:
Create project
automatically.
this._translateService.setMany([
{ sourceText: 'Create project', text: 'Створити проєкт' },
{ sourceText: 'Save', text: 'Зберегти' },
]);Behavior:
- provided keys update reactively
- missing keys reset back to original text
- current language state remains isolated (no stale language mixing)
Programmatic language switch:
await this._translateService.setLanguage('de');this._translateService.setOne({
sourceText: 'Save',
text: 'Зберегти',
});Useful for:
- live editors
- dynamic language loading
- admin translation panels
<h1>{{ 'Create project' | translate }}</h1>Auto-reacts when translations change.
Automatically uses element’s original rendered text as translation key.
<h1 translate>Create project</h1>
<button translate>Save</button>Optional explicit key:
<h1 translate="Create project"></h1>The directive replaces
textContentand is SSR-safe.
Current language can be persisted independently by config:
provideTranslate({
persistLanguage: true,
});Translation payloads are cached per language in-memory.
Old:
provideTranslate([{ sourceText: 'Save', text: 'Speichern' }]);New:
provideTranslate({
language: 'de',
translations: {
de: [{ sourceText: 'Save', text: 'Speichern' }],
},
});Directive and pipe usage stays the same:
[translate]| translate
Copy below code into AGENTS.md file of your project while you are using our plugin.
- This project uses `wacom`, an Angular utility library for shared services, directives, pipes, and app-level configuration.
- Prefer bootstrapping with `provideWacom({...})` in application providers. Use `WacomModule` / `WacomModule.forRoot()` only for legacy NgModule-based apps.
- Put library-wide configuration in `provideWacom()` instead of scattering it across components. Available config areas include `http`, `store`, `meta`, `network`, and optional `socket` / `io`.
- Prefer the library services before adding duplicate app utilities:
- `HttpService` for API calls and shared headers/base URL handling.
- `StoreService` for persisted local storage values.
- `MetaService` for title, description, robots, image, and link tags.
- `CrudService` for data flows that need offline-aware syncing behavior.
- `EmitterService`, `NetworkService`, `SocketService`, `RtcService`, `TimeService`, and `UtilService` when their built-in behavior matches the need.
- Prefer importing the specific Wacom directives, pipes, and translation helpers you need instead of wrapping the whole library again in another shared abstraction.
- For metadata, prefer configuring defaults in `provideWacom({ meta: ... })` and using `MetaService` or route metadata. If route-driven updates are expected, prefer `meta.applyFromRoutes = true`; use `MetaGuard` only when that flow specifically needs a guard.
- For translations, register app translations with `provideTranslate(...)` and use the exported translation pipe/directive rather than creating another parallel translation bootstrap path.
- Keep SSR-safe behavior intact. Do not add unguarded direct access to browser-only globals such as `window`, `document`, storage, media devices, or WebRTC APIs when Wacom already provides a guarded service for that area.
- When changing app behavior, prefer configuring or composing Wacom services first before modifying the library source.
- Common reusable building blocks exported by the library include `clickOutside`, manual form-related directives, translation helpers, and array/search/safe/pagination-style pipes.