Bird
0
0

Consider this Angular service:

medium📝 component behavior Q5 of 15
Angular - Services and Dependency Injection
Consider this Angular service:
@Injectable({ providedIn: 'root' })
export class ClickService {
  clicks = 0;
  registerClick() { this.clicks++; }
}

If two components inject this service and each calls registerClick() once, what will be the value of clicks in the service?
A1
B2
C0
DUndefined, because each component has its own instance
Step-by-Step Solution
Solution:
  1. Step 1: Service providedIn root is singleton

    Both components share the same instance of ClickService.
  2. Step 2: Each call increments the same clicks property

    Two calls total increment clicks from 0 to 2.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    Singleton service shares state across components [OK]
Quick Trick: Singleton service state accumulates across components [OK]
Common Mistakes:
MISTAKES
  • Assuming each component has separate service instance
  • Forgetting that providedIn root creates one shared instance

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes