Bird
0
0

Which is the best way to implement this service-to-service injection pattern?

hard🚀 Application Q15 of 15
Angular - Services and Dependency Injection
You have two services: ApiService and CacheService. You want ApiService to use CacheService to store data before returning it. Which is the best way to implement this service-to-service injection pattern?
AInject CacheService into ApiService constructor and call cache methods inside ApiService
BInject ApiService into CacheService and call API methods inside CacheService
CCreate a third service that duplicates both ApiService and CacheService methods
DUse global variables to share data between ApiService and CacheService
Step-by-Step Solution
Solution:
  1. Step 1: Understand service responsibilities

    ApiService handles API calls, CacheService handles data storage. ApiService should use CacheService to store data.
  2. Step 2: Apply service-to-service injection

    Inject CacheService into ApiService's constructor, then call CacheService methods inside ApiService to store data before returning it.
  3. Step 3: Avoid bad patterns

    Injecting ApiService into CacheService or duplicating methods breaks separation of concerns. Using global variables is bad practice.
  4. Final Answer:

    Inject CacheService into ApiService constructor and call cache methods inside ApiService -> Option A
  5. Quick Check:

    Inject dependent service into main service for clean logic [OK]
Quick Trick: Inject helper service into main service, not vice versa [OK]
Common Mistakes:
MISTAKES
  • Injecting main service into helper service causing circular dependency
  • Duplicating logic instead of reusing services
  • Using global variables instead of injection

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes