Sub topic 5
Making the request depend on signals
This chapter assumes you know TypeScript, Angular components and templates, and the basics of signals (signal, computed, and reading signals in templates). You should also know what a query parameter is. By the end you will know how httpResource decides when to send a request, what it does with the one already running, and what your template sees in between.
The request function is a reactive expression
The first argument to httpResource is a function, not a value. Angular runs it inside a reactive context, the same kind of context a computed uses. Every signal you read while it runs becomes a dependency. When any dependency changes, Angular runs the function again. If the result differs, the resource sends a new request.
user = httpResource<User>(() => `/api/users/${this.userId()}`);Here this.userId() is the only dependency. Calling userId.set(2) makes the function return a new URL, and the resource requests /api/users/2.
You never subscribe, call fetch, or write an effect. The link between the signal and the request is the function itself.
A worked example: paging
The component below pages through a product list. The request function reads one signal, page, and one plain constant, pageSize.
import { Component, computed, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Product {
id: number;
title: string;
}
interface ProductPage {
items: Product[];
total: number;
}
@Component({
selector: 'app-product-list',
template: `
<button (click)="previous()" [disabled]="page() === 1">Previous</button>
<span>Page {{ page() }} of {{ pageCount() }}</span>
<button (click)="next()" [disabled]="page() >= pageCount()">Next</button>
@if (products.isLoading()) {
<p>Loading…</p>
}
@if (products.error()) {
<p>Could not load products.</p>
}
<ul>
@for (p of products.value()?.items; track p.id) {
<li>{{ p.title }}</li>
}
</ul>
`,
})
export class ProductListComponent {
private readonly pageSize = 10;
page = signal(1);
products = httpResource<ProductPage>(() => ({
url: '/api/products',
params: { page: this.page(), limit: this.pageSize },
}));
pageCount = computed(() => {
const total = this.products.value()?.total ?? 0;
return Math.max(1, Math.ceil(total / this.pageSize));
});
next() {
this.page.update((p) => p + 1);
}
previous() {
this.page.update((p) => p - 1);
}
}Clicking "Next" updates page. The request function reruns and returns { url: '/api/products', params: { page: 2, limit: 10 } }. The resource then sends GET /api/products?page=2&limit=10.
The request function can return a plain URL string or a request object. Query parameter values can be strings, numbers, booleans, or arrays of those. Object results are covered in a later chapter. Here the point is that every signal read inside the object is tracked too.
The resource starts as soon as the component is constructed. It does not wait for the template to read it. The first request goes out shortly after creation, and you do not need to trigger it.
What happens when a signal changes
A change to a dependency starts a sequence. Angular reruns the request function, and the resource cancels any request still in flight. It then sends the new request, and the old response is never used.
Cancellation matters when the user acts quickly. If someone clicks "Next" three times in a row, the responses for pages 2 and 3 can arrive after the response for page 4, or never matter at all. Because the resource cancels the older requests, the final state always reflects the latest signal values. You do not need to write a switchMap or compare request IDs.
Status and value during a change
A change to the request is not the same as a call to reload(). The two produce different states.
| Trigger | `status()` | `value()` |
|---|---|---|
| First request, or a changed request | `'loading'` | Reset to `undefined`, or to `defaultValue` if you set one |
| `reload()` on the same request | `'reloading'` | Keeps the previous value |
| Response arrived | `'resolved'` | The new value |
| Request failed | `'error'` | `undefined` (reading `value()` throws if you read it in the error state without a default) |
| Request function returned `undefined` | `'idle'` | `undefined`, or `defaultValue` |
isLoading() is true for both 'loading' and 'reloading'. Use status() when you need to tell them apart.
Reading more than one signal
A request function can read any number of signals. Any of them can trigger a request.
import { Component, computed, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Order {
id: number;
status: string;
}
@Component({
selector: 'app-orders',
template: `
<select (change)="status.set($any($event.target).value)">
<option value="open">Open</option>
<option value="shipped">Shipped</option>
</select>
<button (click)="newestFirst.update((v) => !v)">Flip order</button>
<p>{{ orders.value()?.length ?? 0 }} orders</p>
`,
})
export class OrdersComponent {
status = signal('open');
newestFirst = signal(true);
private sort = computed(() => (this.newestFirst() ? 'desc' : 'asc'));
orders = httpResource<Order[]>(() => ({
url: '/api/orders',
params: { status: this.status(), sort: this.sort() },
}));
}The computed signal sort is a dependency like any other. Flipping newestFirst changes sort, which changes the request. Moving logic into computed signals keeps the request function short and readable.
Several synchronous updates, such as setting status and newestFirst in the same click handler, normally lead to one new request that uses both new values. They do not cause one request per update.
Edge cases and gotchas
Setting a signal to the same value
page.set(1) when page is already 1 does nothing. The signal does not notify, and nothing reruns. Even when a dependency does notify, the request is only replaced if the result differs. A computed value that ends up with the same string, or an object with the same URL and parameters, does not cancel and restart the request.
Plain fields are invisible
Only signals are tracked. Consider this broken version:
import { Component } from '@angular/core';
import { httpResource } from '@angular/common/http';
@Component({
selector: 'app-broken',
template: `<button (click)="userId = userId + 1">Next</button>`,
})
export class BrokenComponent {
userId = 1; // plain number, not a signal
user = httpResource<{ id: number }>(() => `/api/users/${this.userId}`);
}The click changes userId, but nothing tells the resource. The request function never reruns, so no new request is sent. If a value should drive a request, it must be a signal, or a computed built from signals. Inputs declared with input() and route data exposed as signals work the same way.
Reads you do not want tracked
If the function reads a signal you want to ignore, wrap the read in untracked. For example, a "last viewed" signal might be logged in the request but should not trigger a new request.
import { signal, untracked } from '@angular/core';
import { httpResource } from '@angular/common/http';
const userId = signal(1);
const debugLabel = signal('first load');
const user = httpResource<{ id: number }>(() => {
const label = untracked(debugLabel);
console.log('requesting user', userId(), label);
return `/api/users/${userId()}`;
});Changing debugLabel does not send a request. Changing userId does.
Keep the function synchronous
The request function must return its result directly. It cannot be async, and it cannot read signals after an await, because tracking only covers the synchronous part of the call. Do any waiting outside it. Put the result in a signal and read that signal inside the function.
Avoid side effects
Angular may run the function more than once, and it runs whenever a dependency changes. Do not use it to update other signals, write to storage, or call services. Build the request from the current state and return it.
Summary of the model
- The request function runs in a reactive context, and each signal it reads becomes a dependency.
- When a dependency changes, the function reruns. A different result replaces the current request.
- The previous in-flight request is cancelled, so only the latest request can set
value(). - During the replacement,
status()is'loading'andvalue()is reset. Duringreload(),status()is'reloading'andvalue()is kept. - Plain fields,
asynccode, and reads insideuntrackeddo not create dependencies.
Exercise
A component has term = 'angular' as a plain string field, and results = httpResource<string[]>(() => /api/search?q=${this.term}). A button handler sets this.term = 'signals', but no new request is sent. Why, and what is the smallest fix?
Show answer
The request function only tracks signals, and term is a plain field, so changing it never makes the function rerun. Make term a signal with term = signal('angular'), read it as this.term() in the request function, and update it with this.term.set('signals').
Exercise
A user clicks "Next" three times quickly while a page request is still in flight. What happens to the earlier requests, and what do status() and value() show while the last request is running?
Show answer
The resource cancels each earlier in-flight request when the request function returns a new result, so only the last request can set the value. While it runs, status() is 'loading' (and isLoading() is true), and value() is reset to undefined, or to defaultValue if one is configured.