Sub topic 7
Sharing state through a service
This chapter assumes you have the Task interface from the earlier chapters and know the basics of signals: signal(), computed(), and reading a signal by calling it. You should also be comfortable with TypeScript classes and decorators. By the end, you will have one TaskService that owns the task list, and components that read it without owning it.
Why state needs a home
So far, the task list could live inside a single component. That works until a second component needs the same data. A form that adds tasks and a list that shows them are separate components. If each keeps its own array, they disagree.
Passing data through input() and output() fixes this for a parent and its direct children. It gets awkward when the components are far apart in the tree, or when they sit on different routes. A service solves this differently. It is a plain TypeScript class that Angular creates once and hands to any component that asks for it. State lives in the service, and components become thin views over it.
What dependency injection does
Dependency injection (DI) is the mechanism that gives a class the objects it needs, instead of the class constructing them. You do not write new TaskService(). You ask Angular for a TaskService, and Angular finds or creates one.
Three pieces make this work:
- A token identifies what you want. For a service, the token is the class itself.
- A provider tells Angular how to create the value for a token.
- An injector holds the created instances and looks them up. Injectors form a hierarchy: a component's injector falls back to its parent's, and so on up to the root.
The @Injectable({ providedIn: 'root' }) decorator registers a provider with the root injector. Angular creates the instance the first time something requests it, and every later request returns the same object. That single shared object is what makes the service a place to keep shared state.
The service
Here is the complete service. Save it as task.service.ts.
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));
}
}Each part has a job.
A private writable signal
_tasks is a WritableSignal<Task[]>. It is private, so no code outside the class can call set() or update() on it. The underscore prefix is a common convention that frees the plain name tasks for the public view.
A read-only public view
asReadonly() returns a signal that can be read but has no set or update methods. Components can call service.tasks() to get the current array, and the compiler rejects service.tasks.set([]). This is the central design rule of the pattern: state is readable by everyone and writable only through the service's methods. If every change goes through add, toggle, or remove, you can find every place that changes the list by searching one file.
A derived value
remaining is a computed signal. It reads _tasks() inside its function, so Angular records that dependency. When _tasks changes, remaining is marked stale. It recalculates the next time someone reads it, and it caches the result until then. You never write code to keep the count in sync, and it cannot drift from the list.
Immutable updates
Each method gives update() a function that receives the current array and returns a new one:
addspreads the old items into a new array and appends a new task.toggleusesmapto build a new array. It creates a copy of only the matching task ({ ...t, done: !t.done }) and reuses the others.removeusesfilter, which already returns a new array.
This matters because a signal decides whether it changed by comparing the old and new value with Object.is. If you modify the array in place and return the same reference, the signal sees no change. Dependents such as remaining and the template will not update.
The id counter
nextId is an ordinary field, not a signal, because no template reads it. It only guarantees unique ids while the app runs. When tasks come from a server later in this tutorial, the server will assign ids and this counter will go away.
Consuming the service
Components receive the service with inject(). Here is the list component from the previous chapters, now backed by the service.
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);
}
}Some details to notice:
inject()must run in an injection context. A field initializer in a class that Angular constructs is one. A method that runs later, such astoggle, is not. That is whyinject()is called in the field initializer and the result is stored.tasksandremainingare fields that point at the service's signals. They are not copies. The template callstasks()andremaining(), so Angular tracks them as dependencies of this component's view.- The component has no state of its own. It forwards user actions to the service and displays what the service holds.
Any other component can now call inject(TaskService) and see the same list. The form chapter relies on this: its add() call changes the list that this component displays, and neither component knows the other exists.
Where the instance lives
providedIn: 'root' is the default choice, but it is not the only one. The scope of the provider decides how many instances exist.
| Where you provide it | Instances | Typical use |
|---|---|---|
| `@Injectable({ providedIn: 'root' })` | One per application | App-wide state such as this task list |
| `providers: [TaskService]` on a component | One per component instance, shared with its children | State that belongs to one widget |
| `providers` on a route | One per route injector | State scoped to a feature area |
A root-provided service is created lazily when first injected, and it lives until the application is destroyed. That also means its state survives navigation. If the user moves from the list route to a detail route and back, the tasks are still there.
Common errors
- Forgetting the parentheses.
tasksis a signal object.tasks()is the array. In a template,@for (task of tasks; ...)fails to compile with a type error, because a signal is not iterable. In TypeScript code,service.tasks.lengthis also an error. Call the signal first. - Exposing the writable signal. Making
_taskspublic, or returning it from a method, lets any component bypass your methods. Keep it private and exposeasReadonly(). - Putting derived data in a second signal. If you keep a
remainingCountsignal and update it by hand in each method, one forgotten line makes it wrong. Usecomputed. - Calling
inject()outside an injection context. Calling it inside an event handler throws a runtime error sayinginject()must be called from an injection context. Move it to a field initializer or the constructor. - Mutating objects inside the array. Writing
t.done = !t.doneinsidemapchanges the existing object. The array is new, but the object is shared with old references, which can breakOnPushcomponents and any code that kept the old array. Copy the object, astoggledoes.
Trade-offs of this pattern
A signal-based service is a small store without any library. It gives you one source of truth, cheap derived values, and simple testing, since the service is a plain class. The cost is that nothing enforces discipline. Any method you write can change the list in any way, and there is no built-in history or undo.
For a task list, that is the right size. If your state grows into many related collections with complicated update rules, that is the point where a dedicated state library starts to pay for itself. Until then, keep the rule from this chapter: private writable signal, public read-only view, and changes only through methods.
Practice
Exercise
A teammate adds readonly count = computed(() => this._tasks().length); to TaskService, then writes service.tasks().push({ id: 99, title: 'x', done: false }) in a component to add a task quickly. The new task never appears and count does not change. What are the two problems, and how do you fix them?
Show answer
First, push mutates the existing array and the signal's reference stays the same, so the signal never notifies its dependents (count and the template). Second, the component is changing state directly instead of going through the service. Fix both by calling service.add('x'), which uses update() to produce a new array. The tasks signal is typed as read-only data, so components should not change its contents at all.
Exercise
You add providers: [TaskService] to TaskFormComponent. The form's Add button now seems to do nothing, although no error appears. Why, and what is the minimal fix?
Show answer
The component-level provider creates a new TaskService instance for the form, separate from the root instance that TaskListComponent uses. The form adds tasks to its own private list. Remove the providers entry so that inject(TaskService) resolves to the root instance.