Skip to main content
Services are singleton objects that provide specific functionality to your Angular application. They encapsulate business logic, data access, and other operations that can be shared across components.

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 the inject() function:

HTTP Data Service

Services commonly handle HTTP requests:
Using the HTTP service:
Always unsubscribe from observables or use the async pipe to prevent memory leaks.

State Management Service

Services can manage application state:
Using the state management service:

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
  1. Keep services focused - One responsibility per service
  2. Use signals for state - Reactive and performant
  3. Handle errors gracefully - Provide user-friendly error messages
  4. Document public APIs - Make services easy to understand
  5. Write unit tests - Services are easy to test in isolation
  6. Avoid circular dependencies - Structure services hierarchically

Next Steps

Dependency Injection

Deep dive into Angular’s DI system

HTTP Client

Learn about making HTTP requests