Bird
0
0

Which of the following correctly declares an Angular service with @Injectable that is provided at the root injector?

easy📝 Syntax Q3 of 15
Angular - Services and Dependency Injection
Which of the following correctly declares an Angular service with @Injectable that is provided at the root injector?
A@Injectable({ providedIn: 'root' })\nexport class MyService {}
B@Injectable({ providedIn: root })\nexport class MyService {}
C@Injectable({ providedIn: 'app' })\nexport class MyService {}
D@Injectable()\nexport class MyService { providedIn = 'root'; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the syntax for providedIn

    The providedIn property must be a string literal specifying the injector scope, e.g., 'root'.
  2. Step 2: Check each option

    @Injectable({ providedIn: 'root' })\nexport class MyService {} uses the correct syntax with quotes around 'root'. @Injectable({ providedIn: root })\nexport class MyService {} misses quotes, which is invalid. @Injectable({ providedIn: 'app' })\nexport class MyService {} uses 'app' which is not a valid injector scope. @Injectable()\nexport class MyService { providedIn = 'root'; } incorrectly tries to assign providedIn inside the class body.
  3. Final Answer:

    @Injectable({ providedIn: 'root' })\nexport class MyService {} -> Option A
  4. Quick Check:

    Quotes around 'root' are mandatory [OK]
Quick Trick: Always use quotes around providedIn values [OK]
Common Mistakes:
MISTAKES
  • Omitting quotes around 'root'
  • Using invalid strings like 'app'
  • Assigning providedIn inside the class body

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes