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.
Services can be created using the Angular CLI:
ng generate service data
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);
}
Explore 500+ free tutorials across 20+ languages and frameworks.