Why Services?
Components should focus on the screen. Logic that is shared (loading users, a shopping cart, a logger) belongs in a service: a plain class that Angular creates and gives to any component that asks.
Dependency injection (DI): Instead of creating objects yourself with new, you ask Angular for them. Angular builds them, reuses them and can replace them in tests. It is like asking the kitchen for a plate instead of making the plate.
Create a Service
bash
g generate service todo
typescript
import { Injectable, signal, computed } from '@angular/core';
export interface Todo { id: number; title: string; done: boolean; }
@Injectable({ providedIn: 'root' }) // one shared instance for the whole app
export class TodoService {
private readonly _todos = signal<Todo[]>([]);
readonly todos = this._todos.asReadonly();
readonly remaining = computed(() => this._todos().filter(t => !t.done).length);
add(title: string) {
this._todos.update(list => [...list, { id: Date.now(), title, done: false }]);
}
toggle(id: number) {
this._todos.update(list => list.map(t => t.id === id ? { ...t, done: !t.done } : t));
}
remove(id: number) {
this._todos.update(list => list.filter(t => t.id !== id));
}
}
Use It with inject()
typescript
import { Component, inject } from '@angular/core';
@Component({
selector: 'app-todo-page',
template: `
<h2>Todos ({{ service.remaining() }} left)</h2>
<input #box (keyup.enter)="service.add(box.value); box.value = ''" placeholder="New todo">
<ul>
@for (t of service.todos(); track t.id) {
<li [class.done]="t.done">
<input type="checkbox" [checked]="t.done" (change)="service.toggle(t.id)">
{{ t.title }}
<button (click)="service.remove(t.id)">x</button>
</li>
}
</ul>
`,
})
export class TodoPage {
service = inject(TodoService);
}
The older way is constructor injection: constructor(private service: TodoService) {}. Both work. inject() is shorter and works in functions such as guards.
Where Is the Service Created? (Providers and Scopes)
| Where provided | Instance lifetime |
providedIn: 'root' | One instance for the whole app (most common) |
providers in app.config.ts | One instance for the whole app |
providers in a route | One per route (and children), created on first use |
providers in a component | A new instance for each component instance |
typescript
@Component({
selector: 'app-editor',
providers: [EditorState], // every editor gets its own state
template: `...`,
})
export class Editor { state = inject(EditorState); }
Injection Tokens for Configuration
typescript
import { InjectionToken } from '@angular/core';
export const API_URL = new InjectionToken<string>('API_URL');
// app.config.ts
providers: [{ provide: API_URL, useValue: 'https://api.example.com' }]
// service
export class ProductService {
private api = inject(API_URL);
}
| Provider type | Meaning |
useClass | Use another class (for a fake in tests) |
useValue | Use a fixed value |
useFactory | Create the value with a function |
useExisting | Alias to another provider |
Swap a Service in Tests
typescript
TestBed.configureTestingModule({
providers: [{ provide: TodoService, useClass: FakeTodoService }],
});
Rules of Thumb
- Services hold data and logic, components show and collect
- Do not inject a component into a service
- Keep one responsibility per service (
AuthService, CartService)
- Expose state as read-only signals, change it through methods
Conclusion
Create services with @Injectable({ providedIn: 'root' }) and ask for them with inject(). Provide them lower (route or component) when you need separate instances.
Quick Summary: @Injectable + inject(); root = singleton; token for config.