Services & Dependency Injection
In Angular, services are used to write reusable business logic, share data between components, or handle tasks like API calls. Dependency Injection (DI) allows Angular to provide a service to a component automatically.
1. Creating Services
Use Angular CLI to generate a service:
This creates:
Example user.service.ts:
2. Injectable Decorator
The @Injectable decorator makes a class available for DI.
- providedIn: 'root' → Singleton service available app-wide
- providedIn: 'any' → Creates a new instance in each lazy-loaded module
- providedIn: 'platform' → Shared instance across multiple apps on the same platform
3. Service Lifetime
Service instances depend on how they are provided:
- Root: Singleton, one instance for the whole app (most common)
- Platform: Shared instance across multiple Angular apps in the same platform
- Any: New instance for each lazy-loaded module
4. Using Services in Components
Inject the service in a component constructor:
home.component.html
5. Shared State Using Services
Services can store shared data accessible by multiple components:
- Component A updates data in the service
- Component B automatically receives the updated data (if using observables or the same service instance)
Example using a simple array (as above) or a BehaviorSubject for reactive updates.
Summary
- Services contain reusable logic and data
- Use CLI to generate services quickly
@Injectabledecorator makes services available for DI- Service lifetime can be root, platform, or any
- Services help share state and communicate between components