Bird
0
0

Given this service and component code, what will be logged?

medium📝 component behavior Q13 of 15
Angular - Services and Dependency Injection
Given this service and component code, what will be logged?
export class CounterService {
  count = 0;
  increment() { this.count++; }
}

@Component({ selector: 'app-one', template: '' })
export class OneComponent {
  constructor(private counter: CounterService) {}
  ngOnInit() { this.counter.increment(); console.log(this.counter.count); }
}

@Component({ selector: 'app-two', template: '' })
export class TwoComponent {
  constructor(private counter: CounterService) {}
  ngOnInit() { this.counter.increment(); console.log(this.counter.count); }
}
A1 and 2
B1 and 1
C0 and 0
D2 and 2
Step-by-Step Solution
Solution:
  1. Step 1: Understand service instance sharing

    Angular provides the same service instance to both components if the service is singleton.
  2. Step 2: Trace increments and logs

    OneComponent increments count to 1 and logs 1. Then TwoComponent increments to 2 and logs 2.
  3. Final Answer:

    1 and 2 -> Option A
  4. Quick Check:

    Shared service count increments = C [OK]
Quick Trick: Singleton service shares state across components [OK]
Common Mistakes:
MISTAKES
  • Assuming separate service instances per component
  • Ignoring increment effect order
  • Thinking count resets each time

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes