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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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
providersgive 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, andrunInInjectionContext.- 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
Injectoras a field and userunInInjectionContext.
The red pen
Common traps: mistake → fix
Mistake: A service with
@Injectable()is always a singletonFix: only when it is provided once, usually in root.
Mistake:
inject()can be called anywhereFix: only in an injection context.
Easy to hard
Questions interviewers ask, easy to hard
- What does
providedIn: "root"mean? - When would you put a service in a component
providersarray? - Why does inject() fail inside a click handler?
- The cart count resets when users move between sections. How do you find the cause?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.