Skip to main content
current (v21)

API Reference

CatbeeLocalStorageService & CatbeeSessionStorageService

Both services share the same API. The only difference is that CatbeeLocalStorageService persists data across browser sessions, while CatbeeSessionStorageService data is cleared when the browser tab is closed.

Service Aliases
import { CatbeeLocalStorageService, CatbeeSessionStorageService } from '@ng-catbee/storage';

You can also import the services using the shorter aliases:

import { LocalStorageService, SessionStorageService } from '@ng-catbee/storage';

Both pairs refer to the same services respectively.

API Summary


Types

StorageChangeEvent

Event emitted by watchAll().

interface StorageChangeEvent {
key: string | null;
oldValue: string | null;
newValue: string | null;
storageArea: Storage | null;
}

StorageConfig

Configuration interface.

interface StorageConfig {
encoding?: 'default' | 'base64' | 'custom';
customEncode?: (value: string) => string;
customDecode?: (value: string) => string;
}

Basic Methods

set()

Stores a string value in storage.

Method Signature:

set(key: string, value: string, skipEncoding?: boolean): void

Parameters:

  • key - The storage key
  • value - The string value to store
  • skipEncoding - Optional. Skip encoding if true (default: false)

Example:

localStorage.set('username', 'john_doe');
localStorage.set('rawData', 'value', true); // Skip encoding

get()

Retrieves a string value from storage.

Method Signature:

get(key: string, skipDecoding?: boolean): string | null

Parameters:

  • key - The storage key
  • skipDecoding - Optional. Skip decoding if true (default: false)

Returns: The stored value or null if not found

Example:

const username = localStorage.get('username');
if (username) {
console.log('Welcome', username);
}

delete()

Removes an item from storage.

Method Signature:

delete(key: string): void

Parameters:

  • key - The storage key to remove

Example:

localStorage.delete('username');

has()

Checks if a key exists in storage.

Method Signature:

has(key: string): boolean

Parameters:

  • key - The storage key to check

Returns: true if key exists, false otherwise

Example:

if (localStorage.has('authToken')) {
console.log('User is authenticated');
}

clear()

Removes all items from storage.

Method Signature:

clear(): void

Example:

localStorage.clear();

keys()

Returns an array of all storage keys.

Method Signature:

keys(): string[]

Returns: Array of key strings

Example:

const allKeys = localStorage.keys();
console.log('Storage contains:', allKeys);

values()

Returns an array of all storage values.

Method Signature:

values(): (string | null)[]

Returns: Array of values

Example:

const allValues = localStorage.values();

entries()

Returns an array of key-value pairs.

Method Signature:

entries(): [string, string | null][]

Returns: Array of tuples [key, value]

Example:

const entries = localStorage.entries();
for (const [key, value] of entries) {
console.log(`${key}: ${value}`);
}

JSON Methods

setJson()

Stores an object as JSON.

Method Signature:

setJson<T>(key: string, value: T): void

Parameters:

  • key - The storage key
  • value - The object to store

Example:

interface User {
id: number;
name: string;
email: string;
}

const user: User = { id: 1, name: 'John', email: 'john@example.com' };
localStorage.setJson('user', user);

getJson()

Retrieves and parses a JSON value.

Method Signature:

getJson<T>(key: string, skipDecoding?: boolean): T | null

Parameters:

  • key - The storage key
  • skipDecoding - Optional. Skip decoding if true

Returns: The parsed object or null if not found or invalid JSON

Example:

const user = localStorage.getJson<User>('user');
if (user) {
console.log(user.name);
}

getJsonWithDefault()

Retrieves JSON or sets and returns default if missing.

Method Signature:

getJsonWithDefault<T>(key: string, defaultValue: T): T

Parameters:

  • key - The storage key
  • defaultValue - The default value to use if key doesn't exist

Returns: The stored object or default value

Example:

const settings = localStorage.getJsonWithDefault('settings', {
theme: 'light',
language: 'en'
});

updateJson()

Partially updates a JSON object.

Method Signature:

updateJson<T>(key: string, updates: Partial<T>, defaultValue: T): void

Parameters:

  • key - The storage key
  • updates - Partial object with properties to update
  • defaultValue - Default value if key doesn't exist

Example:

// Only update the theme property
localStorage.updateJson('settings', { theme: 'dark' }, {
theme: 'light',
language: 'en'
});

Array Methods

setArray()

Stores an array as JSON.

Method Signature:

setArray<T>(key: string, value: T[]): void

Parameters:

  • key - The storage key
  • value - The array to store

Example:

localStorage.setArray('tags', ['angular', 'typescript', 'rxjs']);

getArray()

Retrieves and parses an array.

Method Signature:

getArray<T>(key: string, skipDecoding?: boolean): T[] | null

Parameters:

  • key - The storage key
  • skipDecoding - Optional. Skip decoding if true

Returns: The parsed array or null if not found or invalid

Example:

const tags = localStorage.getArray<string>('tags');
if (tags) {
console.log('Tags:', tags.join(', '));
}

getArrayWithDefault()

Retrieves array or sets and returns default if missing.

Method Signature:

getArrayWithDefault<T>(key: string, defaultValue: T[] = []): T[]

Parameters:

  • key - The storage key
  • defaultValue - The default array (default: [])

Returns: The stored array or default value

Example:

const tags = localStorage.getArrayWithDefault<string>('tags', ['default']);

Boolean Methods

getBoolean()

Parses a value as boolean. Recognizes: true, false, 1, 0, yes, no, on, off.

Method Signature:

getBoolean(key: string, skipDecoding?: boolean): boolean | null

Parameters:

  • key - The storage key
  • skipDecoding - Optional. Skip decoding if true

Returns: Boolean value or null if not found or invalid

Example:

const isDark = localStorage.getBoolean('darkMode');
if (isDark) {
document.body.classList.add('dark');
}

getBooleanWithDefault()

Parses boolean or sets and returns default if missing.

Method Signature:

getBooleanWithDefault(key: string, defaultValue: boolean): boolean

Parameters:

  • key - The storage key
  • defaultValue - The default boolean value

Returns: Boolean value or default

Example:

const cookiesAccepted = localStorage.getBooleanWithDefault('cookiesAccepted', false);

Number Methods

getNumber()

Parses a value as number.

Method Signature:

getNumber(key: string, skipDecoding?: boolean): number | null

Parameters:

  • key - The storage key
  • skipDecoding - Optional. Skip decoding if true

Returns: Number value or null if not found or invalid

Example:

const count = localStorage.getNumber('viewCount');
if (count !== null) {
console.log('Page views:', count);
}

getNumberWithDefault()

Parses number or sets and returns default if missing.

Method Signature:

getNumberWithDefault(key: string, defaultValue: number): number

Parameters:

  • key - The storage key
  • defaultValue - The default number value

Returns: Number value or default

Example:

const retryCount = localStorage.getNumberWithDefault('retryCount', 0);

Enum Methods

getEnum()

Gets and validates an enum value.

Method Signature:

getEnum<T extends string>(key: string, enumValues: T[], skipDecoding?: boolean): T | null

Parameters:

  • key - The storage key
  • enumValues - Array of valid enum values
  • skipDecoding - Optional. Skip decoding if true

Returns: Enum value if valid or null if not found or invalid

Example:

type Theme = 'light' | 'dark' | 'auto';
const theme = localStorage.getEnum<Theme>('theme', ['light', 'dark', 'auto']);

getEnumWithDefault()

Gets enum or sets and returns default if missing or invalid.

Method Signature:

getEnumWithDefault<T extends string>(key: string, defaultValue: T, enumValues: T[]): T

Parameters:

  • key - The storage key
  • defaultValue - The default enum value
  • enumValues - Array of valid enum values

Returns: Valid enum value or default

Example:

type Language = 'en' | 'es' | 'fr';
const lang = localStorage.getEnumWithDefault<Language>('language', 'en', ['en', 'es', 'fr']);

Advanced Methods

setIfNotExists()

Sets a value only if the key doesn't already exist.

Method Signature:

setIfNotExists(key: string, value: string): void

Parameters:

  • key - The storage key
  • value - The value to set

Example:

// Only set if user hasn't visited before
localStorage.setIfNotExists('firstVisit', new Date().toISOString());

getWithDefault()

Gets value with validation or sets and returns default.

Method Signature:

getWithDefault(key: string, defaultValue: string, allowedValues?: string[]): string

Parameters:

  • key - The storage key
  • defaultValue - The default value
  • allowedValues - Optional. Array of allowed values for validation

Returns: The value or default

Example:

const mode = localStorage.getWithDefault('displayMode', 'grid', ['grid', 'list']);

multiGet()

Retrieves multiple values at once.

Method Signature:

multiGet(keys: string[]): Map<string, string | null>

Parameters:

  • keys - Array of storage keys

Returns: Map of key-value pairs

Example:

const values = localStorage.multiGet(['username', 'email', 'theme']);
const username = values.get('username');
const email = values.get('email');

multiSet()

Sets multiple values at once.

Method Signature:

multiSet(entries: Record<string, string>): void

Parameters:

  • entries - Object with key-value pairs

Example:

localStorage.multiSet({
username: 'john_doe',
email: 'john@example.com',
theme: 'dark'
});

deleteMany()

Deletes multiple keys at once.

Method Signature:

deleteMany(keys: string[]): void

Parameters:

  • keys - Array of storage keys to delete

Example:

localStorage.deleteMany(['tempKey1', 'tempKey2', 'cache']);

size()

Calculates the total size of all stored items in bytes.

Method Signature:

size(): number

Returns: Total size in bytes

Example:

const bytes = localStorage.size();
console.log(`Storage usage: ${bytes} bytes`);

Reactive Methods

watch()

Returns an observable that emits when the specified key changes.

Method Signature:

watch(key: string): Observable<string | null>

Parameters:

  • key - The storage key to watch

Returns: Observable that emits the new value

Example:

localStorage.watch('theme').subscribe(theme => {
console.log('Theme changed to:', theme);
applyTheme(theme);
});

watchAll()

Returns an observable that emits for any storage change.

Method Signature:

watchAll(): Observable<StorageChangeEvent>

Returns: Observable that emits storage change events

Example:

localStorage.watchAll().subscribe(event => {
console.log(`Key "${event.key}" changed from "${event.oldValue}" to "${event.newValue}"`);
});