Question presented to candidate:
"We have a CartService. One teammate put providedIn: 'root' on it, another added it to a component's providers array, and now some screens see an empty cart. Explain the difference between those two ways of providing it."
What a strong answer should cover:
providedIn: 'root'registers the service in the root environment injector: one singleton for the whole app, created on first use, living until the app is destroyed.providers: [CartService]on a component registers it in that component's element injector: a new instance per component instance, shared with that component's children, destroyed with it (itsngOnDestroyruns).- Lookup walks up from the requesting component, so a component-level provider shadows the root one for its subtree; that is why some screens saw a different, empty cart.
- When to use each: root for app-wide state and stateless helpers; component-level for per-widget state that must reset when the widget goes away.
- Root providers are tree-shakable by design (no
providersarray references the class), while a class listed inprovidersis always bundled.
Clarifying questions expected:
- "Should every screen share one cart, or should each widget own its own state?"
- "Is the component that provides it rendered more than once, for example in a list?"
Code / implementation expected: Yes β count instances created and destroyed under each option.