typescript 46 lines · 8 steps

Layered config with an Angular InjectionToken

An injection token supplies analytics defaults that a provider factory layers runtime and override values on top of.

Explained by highlit
1import { InjectionToken, inject, Provider, isDevMode } from '@angular/core';
2import { WINDOW } from './window.token';
3 
4export interface AnalyticsConfig {
5 readonly endpoint: string;
6 readonly flushIntervalMs: number;
7 readonly sampleRate: number;
8 readonly debug: boolean;
9}
10 
11export const ANALYTICS_DEFAULTS: AnalyticsConfig = {
12 endpoint: 'https://collect.example.com/v1/events',
13 flushIntervalMs: 5_000,
14 sampleRate: 1,
15 debug: false,
16};
17 
18export const ANALYTICS_CONFIG = new InjectionToken<AnalyticsConfig>(
19 'ANALYTICS_CONFIG',
20 {
21 providedIn: 'root',
22 factory: () => ({ ...ANALYTICS_DEFAULTS, debug: isDevMode() }),
23 },
24);
25 
26export function provideAnalytics(overrides: Partial<AnalyticsConfig> = {}): Provider {
27 return {
28 provide: ANALYTICS_CONFIG,
29 useFactory: (): AnalyticsConfig => {
30 const win = inject(WINDOW);
31 const runtime = (win as unknown as { __ANALYTICS__?: Partial<AnalyticsConfig> }).__ANALYTICS__ ?? {};
32 const merged: AnalyticsConfig = {
33 ...ANALYTICS_DEFAULTS,
34 debug: isDevMode(),
35 ...runtime,
36 ...overrides,
37 };
38 
39 if (merged.sampleRate < 0 || merged.sampleRate > 1) {
40 throw new Error(`ANALYTICS_CONFIG: sampleRate must be within [0, 1], got ${merged.sampleRate}`);
41 }
42 
43 return Object.freeze(merged);
44 },
45 };
46}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A tree-shakable InjectionToken with a factory gives you a sensible default without requiring any explicit provider registration.
  2. 2Spread order encodes precedence — later sources win, so runtime and caller overrides beat static defaults.
  3. 3Validating and freezing config at construction turns bad input into an early, loud failure instead of a silent bug.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Layered config with an Angular InjectionToken — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code