Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 74 ยท Dependency Injection and Services

Services and Dependency Injection

Learn Angular services and dependency injection - @Injectable, providedIn root, inject() versus constructor injection, singletons, the injector tree and a runnable mini DI container.

Components should be about the page: showing data and reacting to the user. Everything else, such as loading users from a server, remembering the current theme, writing to a log or sharing a shopping cart between pages, belongs in plain classes called services. A service is not a special kind of class. It is an ordinary TypeScript class that Angular knows how to create and hand to whoever asks for it.

The handing-over mechanism is dependency injection (DI). Instead of a component writing new UserService() itself, it declares "I need a UserService" and Angular supplies one. That sounds like a small convenience, but it gives you three big wins: one shared instance where sharing is wanted, easy replacement of a service in tests, and classes that do not need to know how their dependencies are built.

Real versus stand-in. The typescript and html blocks are real Angular and read-only, because the site cannot run the Angular compiler. The runnable examples build a mini DI container of about thirty lines so you can watch the same ideas (lazy creation, singletons, inject(), substitution, circular dependency errors) without Angular. It is a teaching model, not Angular's implementation.

A first service

Here is a service and a component that uses it in real Angular.

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

@Injectable({ providedIn: 'root' })
export class ThemeService {
  private readonly _dark = signal(false);
  readonly dark = this._dark.asReadonly();

  toggle(): void {
    this._dark.update(value => !value);
  }
}
TypeScript
import { Component, inject } from '@angular/core';
import { ThemeService } from './theme.service';

@Component({
  selector: 'app-theme-button',
  template: `
    <button (click)="theme.toggle()">
      {{ theme.dark() ? 'Switch to light' : 'Switch to dark' }}
    </button>
  `,
})
export class ThemeButtonComponent {
  protected readonly theme = inject(ThemeService);
}

Two pieces matter. @Injectable({ providedIn: 'root' }) registers the class with the application's root injector, so it can be injected anywhere and only gets bundled if something actually uses it (it is tree-shakable). And inject(ThemeService) asks the current injector for the instance. If the header and the settings page both inject ThemeService, they receive the same object, which is why a toggle in one is visible in the other.

inject() versus constructor injection

Angular supports two spellings. The inject() function is the modern default, and the older form lists dependencies as constructor parameters. They are equivalent: the compiler reads the parameter types and asks the injector for each.

TypeScript
// Modern: field initializers
export class ReportComponent {
  private readonly users = inject(UserService);
  private readonly logger = inject(LoggerService);
}

// Older, still fully supported: constructor parameters
export class ReportComponent {
  constructor(
    private readonly users: UserService,
    private readonly logger: LoggerService,
  ) {}
}

Prefer inject() in new code. Fields can be readonly and need no constructor, subclasses do not have to forward parameters to super(), it works for functional guards and interceptors that have no constructor at all, and it keeps type inference simple. The one rule is that inject() only works in an injection context: while Angular is constructing a class (field initializers and constructor), or inside a function Angular calls for you, such as a route guard or a factory. Calling it from a click handler or a setTimeout throws an error. If you need to inject later, grab the dependency in a field first.

Singletons and the injector tree

An injector creates each dependency lazily, once, and then reuses it. This is what makes a service a singleton: not a pattern you write, only a consequence of asking the same injector twice.

But an application has more than one injector. There is a root environment injector for the whole app (where providedIn: 'root' services live), further environment injectors for lazy-loaded routes that declare their own providers, and element injectors attached to components and directives. A request walks upward until some injector can answer.

flowchart TD
  P["Platform injector"] --> R["Root environment injector<br/>(providedIn: 'root' services)"]
  R --> L["Lazy route injector<br/>(route-level providers)"]
  R --> C1["App component injector"]
  C1 --> C2["Child component injector<br/>(component providers)"]

Lookups start at the closest injector and move up the tree until a provider is found.

For most services, root scope is right and you never think about the tree. Providers, InjectionToken and Scopes shows how to give a component its own private instance when you need one.

A mini DI container

The container below does what an injector does at its core: it keeps a map from a class to its instance, creates an instance the first time it is requested, and sets a "current injector" so that inject() can find it during construction. Services ask for their dependencies with inject() in field initializers, just like real Angular code.

TypeScript A mini injector with lazy singletons and inject()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read the log in order. Asking for ReportService first creates its dependencies: UserService appears in the log before anything else, and Logger is created silently for both. build() then calls into the already-created services. The three comparisons show the singleton behavior is per injector: the same injector always returns the same instance, while a different injector makes its own. That last point is exactly how component-level providers give each component its own copy of a service.

Why DI pays off: substitution and errors

Because ReportService asks for UserService rather than constructing it, a test can hand it something else. The next example swaps a clock that reads real time for a fixed one. It also shows two failure modes you will meet in practice: calling inject() outside an injection context, and a circular dependency, where two services each need the other. In Angular the circular case reports error NG0200, and the fix is usually to extract the shared part into a third service.

TypeScript Substituting a service, and DI errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Greeter never changes between the two tests; only the injector differs. In real Angular tests you do the same with TestBed.configureTestingModule({ providers: [{ provide: Clock, useValue: fakeClock }] }), covered in Testing Components and Services. The two error messages are the stand-in's own text, but the situations match: real Angular throws when inject() runs outside an injection context, and reports NG0200 for cycles.

Practical guidelines

  • One job per service. UserService talks to the user API, CartService holds the cart, LoggerService logs. A service that does everything becomes the new giant component.
  • Keep state private, expose signals. Hold writable signals privately and expose read-only ones, as in ThemeService above. See Signals in Components.
  • Default to providedIn: 'root'. Narrow the scope only when you need a separate instance per component or route.
  • Services do not know about components. A service should never reference a component or the DOM directly, so that it stays testable and reusable.
  • Do not new a service yourself. You lose sharing, scoping and replaceability, and its own inject() calls would fail.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @Injectable({ providedIn: 'root' }) do?

    Root-provided services are singletons within the root injector, and unused ones are removed from the bundle (tree-shaking).
  2. 2. Where can inject() be called?

    inject() needs a current injector. Outside construction or Angular-invoked functions it throws, so inject early and keep the result in a field.
  3. 3. Two unrelated components inject the same root-provided service. What do they receive?

    An injector creates a dependency once and reuses it, so both components share one object and its state.
  4. 4. Why does DI make testing easier?

    The class asks for a dependency by token and does not build it, so TestBed or a hand-made injector can supply a substitute.
  5. 5. Service A injects B and B injects A. What happens?

    Neither can be created first. Break the cycle by moving shared logic into a third service that both inject.

Summary

  • A service is an ordinary class that holds logic and state outside components; DI creates it and hands it to whoever asks.
  • @Injectable({ providedIn: 'root' }) gives a tree-shakable app-wide singleton; inject() is the modern way to request it, with constructor parameters as the equivalent older style.
  • inject() only works in an injection context.
  • An injector creates each dependency lazily and once; the app has a tree of injectors and lookups walk upward.
  • DI lets tests substitute fakes, and cycles are reported as NG0200.

Next: Providers, InjectionToken and Scopes.