Skip to the page

Dependency injection and change detection · core

Dependency injection and inject()

A provider decides how many instances of a service exist. inject() works only inside an injection context.

The notes

What you must know

  • providedIn: "root": one app-wide instance, created the first time something injects it, and dropped from the bundle if nothing uses it.
  • Component providers: a new instance for each component instance, shared with its children and destroyed with the component. Good for per-widget state.
  • Route providers give an instance for one route tree, created when the user enters it.
  • A service that is provided in two places has two instances. A cart count that resets between sections is the sign: the constructor logs twice, or DevTools shows two injectors.
  • inject() works only in an injection context: field initialisers, the constructor, provider factories, functional guards, resolvers and interceptors, and runInInjectionContext.
  • A click handler runs later, outside that context, so calling inject() there throws NG0203. Fix: private http = inject(HttpClient); as a field.
  • If you must resolve something later, capture the Injector as a field and use runInInjectionContext.

The red pen

Common traps: mistake → fix

  • Mistake: A service with @Injectable() is always a singleton

    Fix: only when it is provided once, usually in root.

  • Mistake: inject() can be called anywhere

    Fix: only in an injection context.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does providedIn: "root" mean?
  2. When would you put a service in a component providers array?
  3. Why does inject() fail inside a click handler?
  4. The cart count resets when users move between sections. How do you find the cause?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview