Angular Services — Create and Inject with Examples
Services
Angular services are a great way to share data among classes that don't know each other. They help organize code, reuse logic across multiple components, share data between components, make API calls, and fetch data from the server. Angular best practices recommend keeping component logic focused on the view - any other logic belongs in a service. In Angular 21, services use @Injectable({ providedIn: 'root' }) to make them available application-wide without needing to add them to any module's providers array.
Creating a Service
Services can be created using the Angular CLI:
ng generate service data
Injectable Service with Signals (Angular 21)
In Angular 21, services use @Injectable({ providedIn: 'root' }) and expose reactive state via Signals. No NgModule providers array needed.
import { Injectable, signal, computed } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CounterService {
private _count = signal(0);
// Read-only public signal
count = this._count.asReadonly();
// Derived signal
doubled = computed(() => this._count() * 2);
increment() { this._count.update(c => c + 1); }
decrement() { this._count.update(c => c - 1); }
reset() { this._count.set(0); }
}
import { Component, inject } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-counter',
standalone: true,
template: `
<h2>Count: {{ counter.count() }}</h2>
<p>Doubled: {{ counter.doubled() }}</p>
<button (click)="counter.increment()">+</button>
<button (click)="counter.decrement()">-</button>
<button (click)="counter.reset()">Reset</button>
`
})
export class CounterComponent {
counter = inject(CounterService);
}
- Services are singleton classes - Angular creates one instance and shares it across all components that inject it.
- Use @Injectable({ providedIn: 'root' }) to make a service available application-wide.
- Services are the right place for business logic, HTTP calls, and shared state - not components.
- Inject services via the constructor or using the inject() function (Angular 14+).
- HttpClient is a service - inject it to make HTTP requests from your services.
- Use RxJS Observables in services to handle async data streams.
Level Up Your Angular Skills
Master Angular with these hand-picked resources