Skip to content

Instantly share code, notes, and snippets.

@e-oz
Last active August 20, 2024 11:38
Show Gist options
  • Save e-oz/4e1e5209a7058bef0ef5f730ace76653 to your computer and use it in GitHub Desktop.
Save e-oz/4e1e5209a7058bef0ef5f730ace76653 to your computer and use it in GitHub Desktop.
singletonOnly
import { isDevMode } from '@angular/core';
const singletons = new Set<symbol>();
export function singletonOnly(unique: symbol) {
if (!isDevMode() || typeof window === 'undefined') {
return;
}
if (singletons.has(unique)) {
const msg = unique.toString() + ' MUST BE A SINGLETON! It was instantiated more than once.';
if (typeof alert !== 'undefined') {
alert(msg);
} else {
console?.trace(msg);
}
} else {
singletons.add(unique);
}
}
@e-oz
Copy link
Author

e-oz commented Aug 9, 2024

Usage example:
File: account-store.ts

const unique = Symbol('AccountStore');

@Injectable({ providedIn: 'root' })  
export class AccountStore {
  constructor() {
    singletonOnly(unique);
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment