Bird
0
0

What will happen if two components inject the same service provided in root and update a shared variable?

medium📝 component behavior Q5 of 15
Angular - Services and Dependency Injection
What will happen if two components inject the same service provided in root and update a shared variable?
@Injectable({ providedIn: 'root' })
export class CounterService { count = 0; }
@Component({ ... }) export class AComponent {
constructor(private svc: CounterService) { this.svc.count++; }
}
@Component({ ... }) export class BComponent {
constructor(private svc: CounterService) { this.svc.count++; }
}
AEach component will have its own count starting at 1
BThe count will reset to 0 after each component runs
CThe count will be 2 shared between both components
DAn error will occur due to multiple injections
Step-by-Step Solution
Solution:
  1. Step 1: Understand singleton service behavior

    Service providedIn root is a singleton shared by all components.
  2. Step 2: Analyze count increments

    Both components increment the same count variable, so total increments add up.
  3. Final Answer:

    The count will be 2 shared between both components -> Option C
  4. Quick Check:

    Singleton service shared state = B [OK]
Quick Trick: Singleton services share state across components [OK]
Common Mistakes:
MISTAKES
  • Thinking each component gets a new service instance
  • Assuming count resets automatically
  • Expecting injection errors for multiple components

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes