Skip to main content

Overview

The @Injectable decorator marks a class as available to be provided and injected as a dependency. It enables Angular’s dependency injection system to provide instances of the class where needed.

Signature

Parameters

Injectable
Optional configuration object that determines how and where the service is provided.

Injectable Options

providedIn

'root' | 'platform' | null
Determines which injector provides the injectable.
  • 'root' - Provided in the root injector (application-level, singleton)
  • 'platform' - Provided in the platform injector (shared across apps)
  • null - Not automatically provided, must be added to a providers array
The providedIn: 'any' option is deprecated. Use 'root' instead.

Basic Service Example

user.service.ts

Service with Dependencies

data.service.ts

Using Services in Components

app.component.ts

Component-Level Providers

notification.service.ts
notification.component.ts
When provided in a component, each instance of the component gets its own instance of the service.

Factory Providers

logger.service.ts
app.config.ts

Class Providers with useClass

config.service.ts
app.config.ts

Value Providers

constants.ts
app.config.ts
Usage:

Inject Function

modern.service.ts
The inject() function is the modern way to inject dependencies. It can be used in constructors, field initializers, and factory functions.

Service Lifecycle

cleanup.service.ts
Services provided in 'root' are singletons and live for the entire application lifetime. They won’t be destroyed until the app is closed. Implement OnDestroy for cleanup, but be aware it may not be called for root services.

Testing Services

user.service.spec.ts

Provider Scopes

Best Practices

  • Use providedIn: 'root' for application-wide services
  • Use component providers for component-specific state
  • Implement OnDestroy for cleanup in services with subscriptions
  • Use inject() function for modern dependency injection
  • Create abstract classes for service interfaces
  • Avoid circular dependencies between services
  • Don’t store component-specific state in root services
  • Be careful with service constructors - keep them lightweight
  • Always unsubscribe from observables to prevent memory leaks

See Also

Dependency Injection

Learn DI fundamentals

Hierarchical Injectors

Understand injector hierarchy

Creating Services

Service creation guide

Providers

Configure providers