Consider an Angular service provided in the root injector. What happens when multiple components inject this service?
Think about how Angular's root injector works for services provided in 'root'.
When a service is provided in the root injector, Angular creates one instance shared across the app. This makes the service a singleton, so all components get the same instance.
Given a singleton service with a counter property initialized to 0, two components increment it by 1 each. What is the final counter value?
export class CounterService { counter = 0; increment() { this.counter++; } } // Component A and Component B both inject CounterService and call increment() once.
Remember the service is a singleton shared by both components.
Since both components share the same service instance, each increment adds 1 to the same counter. So after two increments, the counter is 2.
What happens if you provide a service in the providers array of two different components instead of in root?
Think about how Angular creates injectors for components with providers.
Providing a service in a component's providers array creates a new instance scoped to that component. So each component gets its own instance, breaking the singleton pattern.
Which statement best describes how Angular's hierarchical injectors influence singleton service instances?
Consider how Angular allows overriding services in feature modules or components.
Angular uses a hierarchy of injectors. A service provided in root is a singleton app-wide unless a child injector (like a lazy-loaded module or component) provides its own instance, which overrides the root one locally.
Choose the correct way to provide a singleton service in a standalone Angular component using Angular 17+ syntax.
Remember that providing a service in 'root' makes it singleton app-wide, and standalone components can inject it via constructor.
Option B correctly uses @Injectable({providedIn: 'root'}) to make the service singleton and injects it via constructor in a standalone component. Option B provides the service in the component providers, creating a new instance. Option B provides the service locally without 'providedIn: root', so not singleton. Option B manually creates a new instance, bypassing Angular DI.