Services and Dependency Injection
Services and Dependency Injection
Services in Angular hold reusable logic: API calls, shared data, authentication, and anything several components need. Dependency injection delivers those services to whoever asks for them.
Writing a service
Generate one with the CLI:
ng generate service data
The decorator tells Angular where the service lives:
@Injectable({ providedIn: 'root' })
export class DataService {
private items = [];
getItems() {
return this.items;
}
}
providedIn root makes the service a singleton available everywhere without adding it to a module.
What dependency injection does
Instead of creating services with the new keyword, you list them in the component constructor. Angular creates one instance and hands it over:
constructor(private data: DataService) {}
The private keyword stores the injected instance on the component, so this.data works in methods and templates.
Why services beat duplicated code
When three components need the same data, a single service keeps that logic in one tested place. Components stay thin: they ask for data and render it, while the service owns the fetching and caching details.
Hierarchical injection
Angular providers follow a hierarchy. A service provided in root is app-wide. You can also provide a service inside a component or lazy-loaded route to give it its own fresh instance. This is useful when each screen should hold private state.
Key Points
- Services centralize shared, reusable logic.
- providedIn root registers an app-wide singleton.
- Constructors request services via dependency injection.
- Components stay thin by delegating to services.
- Provider hierarchy controls how long an instance lives.