Sub topic 1
Signals in two minutes
This chapter recaps the parts of Angular signals that the resource API builds on. It is a refresher, not a full introduction. By the end you should be able to explain why a resource's params function behaves like a computed.
Prerequisites
This chapter assumes you already have:
- Working knowledge of TypeScript, including arrow functions and generics.
- Experience writing Angular components and templates, including the
inject()function and component constructors. - A first contact with signals. You have seen
signal(),computed()andeffect(), even if you have not used them much. - A rough idea of what Promises and Observables are. This chapter doesn't use them, but later chapters do.
If signals are new to you, read the official Angular signals guide first and then return here.
What a signal is
A signal is a wrapper around a value that tells Angular when the value changes. You read it by calling it like a function. You write to it with set() or update().
import { signal } from '@angular/core';
const count = signal(0);
console.log(count()); // 0
count.set(5);
console.log(count()); // 5
count.update((n) => n + 1);
console.log(count()); // 6Two details matter later:
- Reading a signal is synchronous and always returns the current value. A signal never holds a Promise of a value unless you put one there.
update()takes a function from the old value to the new value. Use it when the new value depends on the old one.
Derived values with computed
A computed signal derives a value from other signals. It is lazy and cached. The function runs the first time something reads it, and again only after one of the signals it read has changed.
import { computed, signal } from '@angular/core';
const firstName = signal('Ada');
const lastName = signal('Lovelace');
const fullName = computed(() => `${firstName()} ${lastName()}`);
console.log(fullName()); // Ada Lovelace
firstName.set('Grace');
console.log(fullName()); // Grace LovelaceA computed signal is read-only. Calling fullName.set(...) is a compile error. This matters for resources, because a resource's params is also a function that derives something from signals, and you never write to it directly.
Dependency tracking is automatic and dynamic
You never list dependencies by hand. While a computed function runs, Angular records every signal that was read. Those signals become its dependencies for that run.
Dependencies are re-recorded on every run, so they can change. Only the signals actually read during the latest run count:
import { computed, signal } from '@angular/core';
const showDetails = signal(false);
const details = signal('Order #1042');
const label = computed(() => (showDetails() ? details() : 'hidden'));
console.log(label()); // hidden
details.set('Order #2000'); // label does not recompute: details was never read
showDetails.set(true);
console.log(label()); // Order #2000While showDetails is false, details is not a dependency. Changing it costs nothing. You will use this idea when a dependent resource waits for another one. Its params function returns undefined until the data it needs exists, and it only reads the second signal after that.
Effects run side effects
An effect runs a function once, then again whenever any signal it read changes. Use it for work that has to leave the signal world, such as logging, writing to localStorage, or calling a non-signal API.
An effect needs an injection context, so create it in a constructor or a field initializer:
import { Component, computed, effect, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<button (click)="increment()">+1</button>
<p>{{ count() }} doubled is {{ doubled() }}</p>
`,
})
export class CounterComponent {
readonly count = signal(0);
readonly doubled = computed(() => this.count() * 2);
constructor() {
effect(() => {
console.log(`count is now ${this.count()}`);
});
}
increment() {
this.count.update((n) => n + 1);
}
}Effects are scheduled, not immediate. Several set() calls in a row produce one effect run that sees the last value.
The template is a reactive context too. When the template calls count() and doubled(), Angular knows this component depends on them and refreshes it when they change.
Equality: when a write counts as a change
A signal notifies its dependents only when the new value differs from the old one. By default the comparison uses Object.is.
- For numbers, strings and booleans this behaves as you expect.
- For objects and arrays, only a new reference counts as a change.
Mutating in place does nothing visible:
import { signal } from '@angular/core';
const todos = signal<string[]>(['write chapter']);
todos().push('add exercise'); // mutates the array, no notification
console.log(todos().length); // 2, but nothing was told
todos.update((list) => [...list, 'review']); // new array, dependents are notifiedThe first push changes the data, but no dependent is told. Always produce a new object or array when you write. The same rule applies to update() on a resource later in the tutorial.
You can supply your own comparison with the equal option:
import { signal } from '@angular/core';
interface Point {
x: number;
y: number;
}
const point = signal<Point>(
{ x: 0, y: 0 },
{ equal: (a, b) => a.x === b.x && a.y === b.y },
);
point.set({ x: 0, y: 0 }); // equal by value, so no notificationReading without tracking
Sometimes an effect or computed needs a value but should not re-run when it changes. Wrap the read in untracked:
import { Component, effect, signal, untracked } from '@angular/core';
@Component({
selector: 'app-search-log',
template: `<input (input)="query.set($any($event.target).value)" />`,
})
export class SearchLogComponent {
readonly query = signal('');
readonly searchCount = signal(0);
constructor() {
effect(() => {
const q = this.query();
untracked(() => this.searchCount.update((n) => n + 1));
console.log(`search #${this.searchCount()} for "${q}"`);
});
}
}The effect depends on query only. Without untracked, the update() call would read searchCount inside the effect. The effect would then depend on a signal it writes to.
Why this matters for resources
Keep three facts from this chapter in mind:
| Signal feature | What it does | Where it appears in the resource API |
|---|---|---|
| Automatic dependency tracking | Records which signals a function read | `params` re-runs the loader when a signal it read changes |
| Dynamic dependencies | Only signals read in the latest run count | `params` returning `undefined` keeps a resource idle |
| Read-only derived values | You read them but do not write them | `status()`, `error()` and `isLoading()` are read-only signals |
A resource's params function behaves like a computed. It reads signals and returns a value, and Angular tracks what it read. When that value changes, the resource starts a new load. The outputs of the resource (value, status, error) are signals too, so templates and computed functions can read them with no extra wiring.
Common mistakes
- Forgetting the parentheses.
countis the signal object.count()is its value. In a template,{{ count }}prints the function, not the number. - Mutating objects in place. The signal's reference does not change, so nothing updates.
- Creating an effect outside an injection context. Creating one in a plain method throws an error. Put it in a constructor or field initializer, or pass an
injector. - Reading a signal after an
awaitand expecting tracking. Only reads made synchronously while the function runs are tracked. Keep this in mind in the next chapters. It is the reason a resource separatesparams(tracked) fromloader(async, not tracked).
Exercise
Given const a = signal(1); const b = signal(10); const c = computed(() => a() > 0 ? a() : b());, you call c() once and then run b.set(20). Does c recompute the next time it is read? What if you run a.set(-1) instead?
Show answer
After b.set(20), c does not recompute. In the last run a() > 0 was true, so only a was read, and b is not a dependency. After a.set(-1), c recomputes on the next read. The condition is now false, so it reads b() and returns the current value of b. From that run on, b is also a dependency.
Exercise
A component has readonly items = signal<number[]>([1, 2]). A method runs this.items().push(3), but the template that renders the list does not change. Why, and how do you fix it?
Show answer
push mutates the same array. The signal's value keeps the same reference, so the default Object.is equality sees no change and notifies no one. Replace the value instead, for example this.items.update((list) => [...list, 3]).