Bird
0
0

Which is the correct way to inject a service into an Angular component constructor?

easy📝 Syntax Q12 of 15
Angular - Services and Dependency Injection
Which is the correct way to inject a service into an Angular component constructor?
Aconstructor() { this.myService = MyService; }
Bconstructor(myService = new MyService()) {}
Cconstructor(public myService) {}
Dconstructor(private myService: MyService) {}
Step-by-Step Solution
Solution:
  1. Step 1: Recall Angular dependency injection syntax

    Angular injects services by declaring them as private/public in the constructor parameters.
  2. Step 2: Check each option

    constructor(private myService: MyService) {} uses correct syntax with private and type annotation. Others create instances manually or miss type.
  3. Final Answer:

    constructor(private myService: MyService) {} -> Option D
  4. Quick Check:

    Use private with type in constructor = D [OK]
Quick Trick: Use private and type in constructor for services [OK]
Common Mistakes:
MISTAKES
  • Manually creating service instances
  • Missing type annotation
  • Assigning service without new keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes