Bird
0
0

You want to create a service that is only available inside a specific feature module, not app-wide. Which is the best way to configure @Injectable and providedIn to achieve this?

hard🚀 Application Q15 of 15
Angular - Services and Dependency Injection
You want to create a service that is only available inside a specific feature module, not app-wide. Which is the best way to configure @Injectable and providedIn to achieve this?
AUse <code>@Injectable()</code> without providedIn and add the service to the feature module's providers array
BUse <code>@Injectable({ providedIn: FeatureModule })</code> where FeatureModule is the module class
CUse <code>@Injectable({ providedIn: 'root' })</code> and import the service in the feature module
DUse <code>@Injectable({ providedIn: 'any' })</code> to limit service to the feature module
Step-by-Step Solution
Solution:
  1. Step 1: Understand providedIn options

    Using providedIn: 'root' makes the service app-wide singleton, so not limited to a feature module.
  2. Step 2: Provide service only in feature module

    Using providedIn: FeatureModule where FeatureModule is the NgModule class is possible but not officially recommended or supported in all Angular versions. The standard way is to omit providedIn and add the service to the feature module's providers array.
  3. Step 3: Evaluate other options

    providedIn: 'any' creates a new instance in each injector but does not restrict to a single module. Importing with providedIn: 'root' makes it app-wide.
  4. Final Answer:

    Use @Injectable() without providedIn and add the service to the feature module's providers array -> Option A
  5. Quick Check:

    Omitting providedIn and adding to providers array scopes service to module [OK]
Quick Trick: Omit providedIn and add to feature module providers for module scope [OK]
Common Mistakes:
MISTAKES
  • Using providedIn: 'root' for feature-only service
  • Using providedIn: FeatureModule which is not standard
  • Misunderstanding providedIn: 'any' scope

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes