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
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
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.