Chapter 06

Services and dependency injection

Components render. Services do everything else. Angular's injector decides which instance each component receives — and that seam is what makes the whole application testable.

⏱ 15 min readLevel: intermediate

A service

core/auth/auth.service.ts
import { computed, inject, Injectable, signal } from '@angular/core';
import { Router } from '@angular/router';

@Injectable({ providedIn: 'root' })     // one instance for the whole app
export class AuthService {
  private readonly router = inject(Router);
  private readonly api = inject(AuthApi);

  private readonly token = signal<string | null>(
    localStorage.getItem('token'));

  readonly isAuthenticated = computed(() => this.token() !== null);
  readonly claims = computed(() => decodeJwt(this.token()));
  readonly roles  = computed(() => this.claims()?.roles ?? []);

  hasRole(role: string): boolean {
    return this.roles().includes(role);
  }

  async login(email: string, password: string): Promise<void> {
    const { accessToken } = await this.api.login(email, password);
    localStorage.setItem('token', accessToken);
    this.token.set(accessToken);
  }

  logout(): void {
    localStorage.removeItem('token');
    this.token.set(null);
    this.router.navigate(['/login']);
  }

  currentToken(): string | null {
    return this.token();
  }
}
providedIn: 'root' is tree-shakable

If nothing injects the service, it is removed from the bundle entirely. That is why it is preferred over listing services in a providers array — which always ships them.

inject() vs the constructor

both work; one is nicer
// classic — still perfectly valid
export class OrderListComponent {
  constructor(
    private readonly store: OrderStore,
    private readonly router: Router,
  ) {}
}

// modern — no constructor, works in field initialisers
export class OrderListComponent {
  private readonly store  = inject(OrderStore);
  private readonly router = inject(Router);

  // and it composes: a reusable function that injects
  readonly orders = this.store.orders;
}

// inject() also works inside standalone FUNCTIONS,
// which is what makes functional guards and interceptors possible
export const adminGuard: CanActivateFn = () => {
  const auth = inject(AuthService);
  const router = inject(Router);
  return auth.hasRole('ADMIN') || router.createUrlTree(['/forbidden']);
};
inject() only works in an injection context

That means field initialisers, constructors, factory functions, guards, interceptors and effect() callbacks. Calling it inside ngOnInit or an event handler throws NG0203. If you must defer, capture inject(Injector) first and use runInInjectionContext.

Provider scopes

Where you provide itInstancesUse for
providedIn: 'root'One, application-wideAuth, config, most stores — the default
providers on a routeOne per activation of that route subtreeFeature state that should reset on leaving
providers on a componentOne per component instancePer-widget state, e.g. a wizard
providedIn: 'platform'Shared across bootstrapped appsMicro-frontends. Rare.
route-scoped state that resets automatically
export const routes: Routes = [
  {
    path: 'orders',
    providers: [OrderStore],          // fresh store each time the user enters
    loadChildren: () => import('./features/orders/routes')
                          .then(m => m.ORDER_ROUTES),
  },
];

Injection tokens

Interfaces disappear at compile time, so they cannot be injected. Use a token.

core/config/app-config.token.ts
export interface AppConfig {
  apiUrl: string;
  pageSize: number;
  features: { export: boolean; bulkEdit: boolean };
}

export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG', {
  providedIn: 'root',
  factory: () => ({
    apiUrl: '/api',
    pageSize: 25,
    features: { export: true, bulkEdit: false },
  }),
});

// override at bootstrap
providers: [
  { provide: APP_CONFIG, useValue: loadRuntimeConfig() },
]

// consume
export class OrderApi {
  private readonly config = inject(APP_CONFIG);
}

Swapping implementations

abstract class as the contract
export abstract class PaymentGateway {
  abstract charge(orderId: number, amount: number): Promise<PaymentResult>;
}

@Injectable()
export class StripeGateway extends PaymentGateway { /* ... */ }

@Injectable()
export class FakeGateway extends PaymentGateway {
  async charge(): Promise<PaymentResult> {
    return { status: 'APPROVED', reference: 'fake-1' };
  }
}

providers: [
  { provide: PaymentGateway,
    useClass: environment.production ? StripeGateway : FakeGateway },
]

An abstract class works as both the type and the injection token, so you avoid a separate InjectionToken for the common case.

Provider formSupplies
useClassA different class for the same token
useValueA constant object
useFactoryA function, with deps injected
useExistingAn alias to another token
multi: trueContributes to an array — how interceptors work

Designing services worth having

  • One responsibility. An OrderApi that only talks HTTP, and an OrderStore that only holds state, beat one OrderService that does both.
  • Expose signals, not raw state. Keep the writable signal private; publish computed() selectors.
  • No DOM access. Services must survive server-side rendering.
  • Return domain types. Map API shapes to your own interfaces at the boundary, so a backend rename touches one file.
  • Do not inject a component into a service. If you need to, the dependency is backwards.

You call inject(Router) inside a click handler and get NG0203. Why?

Angular only knows which injector to use while it is constructing something. Move the call to a field initialiser (private router = inject(Router)) — the usual fix — or capture an Injector and wrap the later call in runInInjectionContext.