Bird
0
0

How can you ensure a service is tree-shakable and only included if used in the app?

hard🚀 Application Q9 of 15
Angular - Services and Dependency Injection
How can you ensure a service is tree-shakable and only included if used in the app?
AProvide the service in a lazy-loaded module only.
BUse <code>@Injectable({ providedIn: 'root' })</code> in the service.
CDeclare the service without @Injectable decorator.
DManually add the service to the providers array in AppModule.
Step-by-Step Solution
Solution:
  1. Step 1: Understand tree-shakable providers

    Using providedIn: 'root' enables Angular to tree-shake unused services.
  2. Step 2: Compare with manual providers

    Manually adding to providers array prevents tree-shaking because Angular always includes it.
  3. Final Answer:

    Use @Injectable({ providedIn: 'root' }) in the service. -> Option B
  4. Quick Check:

    providedIn 'root' enables tree-shaking [OK]
Quick Trick: Use providedIn 'root' for tree-shakable services [OK]
Common Mistakes:
MISTAKES
  • Adding service manually disables tree-shaking
  • Omitting @Injectable disables injection
  • Assuming lazy module alone ensures tree-shaking

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes