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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A tree-shakable InjectionToken with a factory gives you a sensible default without requiring any explicit provider registration.
- 2Spread order encodes precedence — later sources win, so runtime and caller overrides beat static defaults.
- 3Validating and freezing config at construction turns bad input into an early, loud failure instead of a silent bug.
Related explainers
php
final class InvoiceCalculator { private const SCALE = 4;
Precise money math with PHP's BCMath
bcmath
arbitrary precision
money
Intermediate
8 steps
javascript
const IBAN_LENGTHS = { DE: 22, FR: 27, GB: 22, ES: 24, IT: 27, NL: 18, BE: 16, CH: 21, AT: 20, PT: 25, };
How IBAN validation works in JavaScript
validation
checksum
modular-arithmetic
Intermediate
8 steps
typescript
import { useCallback, useRef, useState } from "react"; type UploadZoneProps = { accept?: string[];
A drag-and-drop file upload zone in React
drag-and-drop
file-validation
controlled-state
Intermediate
9 steps
go
func UploadDocument(c *gin.Context) { fileHeader, err := c.FormFile("file") if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
Handling multipart uploads in Gin
multipart-upload
validation
error-handling
Intermediate
9 steps
typescript
import { useState, useEffect, useRef, useCallback } from "react"; interface Suggestion { id: string;
A debounced autocomplete hook in React
debounce
custom-hooks
abortcontroller
Advanced
7 steps
typescript
import { Body, Controller, Ip, Post, UnauthorizedException } from '@nestjs/common'; import { Throttle, ThrottlerGuard } from '@nestjs/throttler'; import { UseGuards } from '@nestjs/common'; import { AuthService } from './auth.service';
Rate-limiting an auth flow in NestJS
rate-limiting
authentication
guards
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/layered-config-with-an-angular-injectiontoken-explained-typescript-e760/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.