javascript / expert
Snippet
Symbol-Based Private State Encapsulation with WeakMap Storage in Angular Services
Combining JavaScript Symbol primitive datatypes with WeakMap memory structures provides true private encapsulation in Angular services. Unlike standard TypeScript private access modifiers which disappear after transpilation, WeakMap entries keyed by service instances prevent memory leaks and block external runtime object introspection.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { Injectable } from '@angular/core';const SECRET_KEY = Symbol('InternalVaultKey');const vaultStorage = new WeakMap<object, Map<symbol, unknown>>();@Injectable({ providedIn: 'root' })export class SecureVaultService {constructor() {vaultStorage.set(this, new Map());}setPrivateSecret(secret: string): void {const internalStore = vaultStorage.get(this);if (internalStore) {internalStore.set(SECRET_KEY, Object.freeze({ token: secret, timestamp: Date.now() }));}}getPrivateSecret(): { token: string; timestamp: number } | null {const internalStore = vaultStorage.get(this);const data = internalStore?.get(SECRET_KEY);return data ? (data as { token: string; timestamp: number }) : null;}}
angular
Breakdown
1
const SECRET_KEY = Symbol('InternalVaultKey');
Instantiates a unique, non-enumerable primitive Symbol key for indexing sensitive service metadata.
2
const vaultStorage = new WeakMap<object, Map<symbol, unknown>>();
Allocates a WeakMap holding weak object references to service instances to prevent memory leakage upon garbage collection.
3
internalStore.set(SECRET_KEY, Object.freeze({ token: secret, timestamp: Date.now() }));
Stores an immutable object record mapped to the unique Symbol key within the service's private container.
4
return data ? (data as { token: string; timestamp: number }) : null;
Retrieves and casts the private state object safely without exposing internal storage structures.