1. Services in Angular
Definition:
A service is a class in Angular that contains logic, data, or functionality that can be shared across multiple components. Services are used to separate concerns, meaning components handle the view, while services handle business logic or data fetching.
Common uses of services:
- Fetching data from APIs (HTTP requests)
- Storing shared state or variables
- Utility functions (e.g., formatting, calculations)
- Authentication logic
- Logging
Example of a service:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // This makes the service available globally
})
export class DataService {
private data: string[] = [];
constructor() {}
addData(item: string) {
this.data.push(item);
}
getData(): string[] {
return this.data;
}
}
- The
@Injectable
decorator marks this class as a service that can be injected. providedIn: 'root'
makes the service singleton and available application-wide.
2. Dependency Injection (DI) in Angular
Definition:
Dependency Injection (DI) is a design pattern in which a class receives its dependencies from an external source rather than creating them itself. Angular has a built-in DI framework that automatically provides instances of services where needed.
Why DI?
- Promotes loose coupling (components don’t need to know how services are created)
- Makes testing easier (can replace services with mocks)
- Reuse services across multiple components
Using a service with DI:
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-my-component',
template: `
<button (click)="addItem()">Add Item</button>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
`
})
export class MyComponent {
items: string[] = [];
// Inject the service via the constructor
constructor(private dataService: DataService) {}
addItem() {
this.dataService.addData('New Item');
this.items = this.dataService.getData();
}
}
How it works:
- Angular sees
private dataService: DataService
in the constructor. - Angular injects a singleton instance of
DataService
. - The component can now use
DataService
methods without creating it manually.
3. Providers in Angular DI
- A provider tells Angular how to create a service.
- There are three ways to provide a service:
- Root-level provider (
@Injectable({ providedIn: 'root' })
)- Singleton across the app
- Most common approach
- Module-level provider (in
providers
array of NgModule)- Singleton within that module
- Component-level provider (in
providers
array of Component)- Creates a new instance for that component and its children
4. Key Points
- Services = reusable logic/data containers.
- DI = Angular automatically provides service instances where needed.
- Use
@Injectable({ providedIn: 'root' })
for most global services. - Component-level providers create separate instances (useful for isolated state).