What are Services?
Services are TypeScript classes that:- Contain reusable business logic
- Manage application state
- Handle data access (HTTP requests, local storage)
- Provide utilities and helper functions
- Enable communication between components
Services promote the single responsibility principle by separating business logic from presentation logic in components.
Creating a Service
Create a service using the@Injectable decorator:
Using Services in Components
Inject services using theinject() function:
HTTP Data Service
Services commonly handle HTTP requests:State Management Service
Services can manage application state:Logger Service
Utility service for logging:Communication Between Components
Use services to share data between unrelated components:Service with Dependencies
Services can depend on other services:Best Practices
Single Responsibility
Each service should have one clear purpose
Use providedIn: 'root'
For application-wide singletons
Return Observables
For asynchronous operations
Use Signals
For reactive state management
- Keep services focused - One responsibility per service
- Use signals for state - Reactive and performant
- Handle errors gracefully - Provide user-friendly error messages
- Document public APIs - Make services easy to understand
- Write unit tests - Services are easy to test in isolation
- Avoid circular dependencies - Structure services hierarchically
Next Steps
Dependency Injection
Deep dive into Angular’s DI system
HTTP Client
Learn about making HTTP requests
