What is Angular Services - Types of services in Angular with Examples
Estimated study time: 9 minutes. Keeping business logic and shared data out of your components.
A service is a class dedicated to a specific piece of logic — fetching data, sharing state, handling authentication — that's kept separate from components so it can be reused and tested independently.
Why Use Services?
Components should focus on presenting data, not fetching or transforming it. Moving that logic into a service keeps components lean and lets multiple components share the same logic without duplication.
Creating a Basic Service
@Injectable({ providedIn: 'root' })
export class ProductService {
constructor(private http: HttpClient) {}
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>('/api/products');
}
}
Common Types of Services
- Data services — wrap HTTP calls to a backend API.
- State services — hold and broadcast shared application state via observables.
- Utility services — reusable helper logic like formatting, validation, or logging.
- Authentication services — manage login state, tokens, and route guards.
Using a Service in a Component
export class ProductListComponent implements OnInit {
products: Product[] = [];
constructor(private productService: ProductService) {}
ngOnInit() {
this.productService.getProducts().subscribe(data => this.products = data);
}
}
Service Scope
providedIn: 'root' makes a service a singleton shared across the entire app. You can also scope a service to a specific module or component if you need a fresh instance per feature.