What is a Provider?
A provider is an instruction to the Dependency Injection system on how to obtain a value for a dependency. Most of the time, you provide a service class, and Angular creates a singleton instance. However, as an architect, you might need to provide a constant value, a different class based on a condition, or a factory function to handle complex initialization logic.
- The 'providedIn' Property
Modern Angular recommends providing services directly in the @Injectable decorator using the providedIn property. Using 'root' makes the service a singleton available application-wide and enables 'tree-shaking', meaning the service is only included in the final bundle if it is actually used.
- Provider Recipes
When you need more control, you define providers in an NgModule or a Component. This is where you can swap implementations—perfect for your Revochamp engine when switching between a real AI API and a local mock.
- useClass: Provides a specific class for an injection token.
- useValue: Provides a simple fixed value (like a configuration object).
- useExisting: Maps one token to another existing token (alias).
- useFactory: Uses a function to dynamically create the dependency.
The Injection Hierarchy
Angular's DI system is hierarchical. If a component requests a dependency, Angular looks at that component's providers, then its parent's, and so on, until it reaches the root.
Provider Strategies Comparison
| Recipe | When to Use | Example |
|---|---|---|
| useClass | Default; swapping implementations | Mocking an API service |
| useValue | Fixed data or configurations | API Keys or feature flags |
| useFactory | Complex setup involving logic | Service that needs specific initialization |
| providedIn: 'root' | Standard singletons | Most application services |