TExcelTAD
Home › Angular › Services & Dependency Injection

Services & Dependency Injection

Components should focus on presenting data and handling user interaction. Logic that is shared between components — fetching data, keeping a shopping cart, logging, authentication — belongs in services. Angular's dependency injection (DI) system creates those services and hands them to whoever asks.

Creating a service

A service is a class marked with @Injectable. Generate one with ng generate service cart:

ts
import { Injectable, computed, signal } from '@angular/core';

export interface CartItem { id: number; name: string; price: number; }

@Injectable({ providedIn: 'root' })
export class Cart {
  private readonly _items = signal<CartItem[]>([]);
  readonly items = this._items.asReadonly();
  readonly total = computed(() => this._items().reduce((s, i) => s + i.price, 0));

  add(item: CartItem) {
    this._items.update((list) => [...list, item]);
  }

  clear() {
    this._items.set([]);
  }
}

providedIn: 'root' registers the service with the application's root injector: there is one shared instance for the whole app, created lazily the first time someone asks for it. If nobody ever injects it, it is removed from the bundle (tree-shaking).

Injecting a service

Use the inject() function in a field initializer (or the constructor). Two components that inject Cart receive the same instance, so they share state:

angular · try it yourself
import { Component, inject } from '@angular/core';
import { Cart } from './cart';

@Component({
  selector: 'app-catalog',
  template: `
    <button (click)="cart.add({ id: 1, name: 'Desk lamp', price: 35 })">Add lamp</button>
    <button (click)="cart.add({ id: 2, name: 'Plant', price: 12 })">Add plant</button>
  `,
})
export class Catalog {
  protected cart = inject(Cart);
}

@Component({
  selector: 'app-cart-summary',
  template: `<p>🛒 {{ cart.items().length }} items · {{ cart.total() }} USD</p>`,
})
export class CartSummary {
  protected cart = inject(Cart);
}

@Component({
  selector: 'app-root',
  imports: [Catalog, CartSummary],
  template: `<app-cart-summary /><app-catalog />`,
})
export class App {}

The preview shows the state after clicking each button once. Catalog changed the cart and CartSummary updated — they never talk to each other directly.

Note: You may also see constructor injection: constructor(private cart: Cart) {}. It works the same way; inject() is the style used in current Angular docs because it works well with field initializers and functions such as guards.

How an injector works

At its heart, an injector is a map from a token (usually a class) to an instance, plus a rule for creating missing instances. This plain TypeScript version shows the singleton behaviour:

ts · try it yourself
type Ctor<T> = new (injector: Injector) => T;

class Injector {
  private instances = new Map<Ctor<unknown>, unknown>();

  get<T>(token: Ctor<T>): T {
    if (!this.instances.has(token)) {
      console.log(`creating ${token.name}`);
      this.instances.set(token, new token(this));
    }
    return this.instances.get(token) as T;
  }
}

class Logger {
  lines: string[] = [];
  log(msg: string) { this.lines.push(msg); }
}

class CartService {
  private logger: Logger;
  items: string[] = [];
  constructor(injector: Injector) {
    this.logger = injector.get(Logger); // a dependency of a dependency
  }
  add(item: string) {
    this.items.push(item);
    this.logger.log(`added ${item}`);
  }
}

const root = new Injector();
root.get(CartService).add('lamp');
root.get(CartService).add('plant');

console.log(root.get(CartService).items);
console.log(root.get(Logger).lines);
console.log('same instance?', root.get(CartService) === root.get(CartService));
creating CartService
creating Logger
[ 'lamp', 'plant' ]
[ 'added lamp', 'added plant' ]
same instance? true

Where services can be provided

Where Scope
@Injectable({ providedIn: 'root' }) One instance for the whole app (most common)
providers: [X] in app.config.ts App-wide, configured at bootstrap
providers: [X] in a route definition Shared by that route and its children
providers: [X] in @Component A new instance for each instance of that component and its children

Component-level providers are useful for state that belongs to one widget — for example, each open editor tab gets its own EditorState.

Injection tokens for non-class values

Configuration values aren't classes, so you create an InjectionToken to use as the key:

ts
import { InjectionToken, inject } from '@angular/core';

export const API_URL = new InjectionToken<string>('API_URL');

// app.config.ts
providers: [{ provide: API_URL, useValue: 'https://api.example.com' }]

// anywhere
const baseUrl = inject(API_URL);

Why DI?

  • Sharing — one instance, many consumers.
  • Testing — in a test you can provide a fake: { provide: Cart, useValue: fakeCart }.
  • Decoupling — components ask for what they need, not how to build it.

Test yourself

What does providedIn: 'root' mean?

  1. A new instance per component
  2. One shared instance for the entire application
  3. The service runs on the server only
  4. The service is created eagerly at startup no matter what

Which function retrieves a dependency inside a component field initializer?

  1. provide()
  2. inject()
  3. require()
  4. useService()

You add providers: [EditorState] to a component's decorator. How many EditorState instances exist when the component appears 3 times?

  1. 1
  2. 3
  3. 0
  4. Depends on the route