Sub topic 7
Sharing state through a service
This chapter assumes you know TypeScript classes, the Task interface from the earlier chapter, and the basics of signals and standalone components. Here you move the task state out of a single component and into an injectable service, so any component can read and change it.
Why a service
If TaskListComponent owns the tasks, a sibling such as a form cannot reach them without passing data through a parent. A service solves this. Angular creates one instance and hands it to every class that asks for it. This mechanism is called dependency injection (DI).
With providedIn: 'root', Angular creates a single instance for the whole application, and every component that injects it sees the same state.
The service
import { Injectable, computed, signal } from '@angular/core';
import { Task } from './task';
@Injectable({ providedIn: 'root' })
export class TaskService {
private readonly _tasks = signal<Task[]>([]);
private nextId = 1;
readonly tasks = this._tasks.asReadonly();
readonly remaining = computed(() => this._tasks().filter(t => !t.done).length);
add(title: string): void {
this._tasks.update(list => [...list, { id: this.nextId++, title, done: false }]);
}
toggle(id: number): void {
this._tasks.update(list => list.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
}
remove(id: number): void {
this._tasks.update(list => list.filter(t => t.id !== id));
}
}Three decisions here matter:
- A private writable signal.
_taskscan be changed only inside the service. - A read-only view.
asReadonly()gives components a signal they can read by callingtasks(), but they cannot callsetorupdateon it. - Immutable updates. Each method returns a new array, and
togglereturns a new object for the changed task. Signals notify dependents when the value changes by reference, so mutating the array in place would not trigger updates.
remaining is a computed signal. It recalculates only when _tasks changes, and it caches the result between reads.
Injecting the service
Use inject() in a field initializer:
import { Component, inject } from '@angular/core';
import { TaskService } from './task.service';
@Component({
selector: 'app-task-list',
template: `
<ul>
@for (task of tasks(); track task.id) {
<li>
<input type="checkbox" [checked]="task.done" (change)="toggle(task.id)" />
<span [class.done]="task.done">{{ task.title }}</span>
<button type="button" (click)="remove(task.id)">Delete</button>
</li>
} @empty {
<li>No tasks yet.</li>
}
</ul>
<p>{{ remaining() }} remaining</p>
`,
})
export class TaskListComponent {
private readonly service = inject(TaskService);
readonly tasks = this.service.tasks;
readonly remaining = this.service.remaining;
toggle(id: number): void {
this.service.toggle(id);
}
remove(id: number): void {
this.service.remove(id);
}
}The component stores no task data of its own. It exposes the service's signals and forwards user actions to the service methods. When any component calls add, this list updates without further wiring.
Common errors
- Mutating the array.
list.push(task)insideupdatereturns the same reference, so the signal sees no change and the view may not refresh. Return a new array. - Forgetting to call the signal. In the template, write
tasks(), nottasks. Without the call you pass the signal function itself to@for. - Calling
inject()too late.inject()works only in an injection context, such as a field initializer or constructor. Calling it insidetoggle()throws an error. - Providing the service twice. If you also list
TaskServicein a component'sproviders, that component gets its own separate instance and stops sharing state.
Exercise
Why does the service expose this._tasks.asReadonly() instead of making tasks a public writable signal?
Show answer
A read-only signal lets components read the tasks but not call set or update on them. All changes then go through add, toggle, and remove, so the rules for changing state live in one place.
Exercise
A teammate writes remove(id) as this._tasks().splice(index, 1). What goes wrong, and how do you fix it?
Show answer
splice mutates the existing array and the signal's value reference does not change, so dependents such as remaining and the @for block may not update. Use this._tasks.update(list => list.filter(t => t.id !== id)) to produce a new array.