Sub topic 7
Request objects: params, headers, method and body
This chapter assumes you can write Angular components with signals and that you know the basics of HTTP: methods, query parameters, headers and request bodies. It also assumes you have a working httpResource and have called provideHttpClient(), as covered earlier in this tutorial.
From a string to a request object
The request function you pass to httpResource can return three kinds of value:
- A string, which is the URL of a GET request.
undefined, which keeps the resource idle.- A request object, which describes the whole request.
A string is shorthand for a request object that has only a url. These two resources are equivalent:
import { httpResource } from '@angular/common/http';
export const a = httpResource<unknown>(() => '/api/products');
export const b = httpResource<unknown>(() => ({ url: '/api/products' }));Use the object form when you need anything beyond the URL. The main fields are:
| Field | Type | Purpose |
|---|---|---|
| `url` | `string` | The address to request. Required. |
| `method` | `string` | The HTTP method. Defaults to `GET`. |
| `params` | `HttpParams` or a record | Query string parameters. |
| `headers` | `HttpHeaders` or a record | Request headers. |
| `body` | any serializable value | The request body. |
| `withCredentials` | `boolean` | Send cookies on cross-site requests. |
| `context` | `HttpContext` | Metadata that interceptors can read. |
| `transferCache` | `boolean` or an options object | Control reuse of server-rendered responses. |
The request object also accepts reportProgress and, in recent Angular versions, a few Fetch options such as keepalive and priority. Check the Angular version you target before relying on those.
Query parameters
You can build a query string by hand inside the URL, but the params field is safer. Angular encodes each key and value for you, so a search term such as a&b=c cannot break the query.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Product {
id: number;
title: string;
}
@Component({
selector: 'app-product-list',
template: `
<button (click)="page.set(page() + 1)">Next page</button>
<p>Page {{ page() }}</p>
<ul>
@for (p of products.value(); track p.id) {
<li>{{ p.title }}</li>
}
</ul>
`,
})
export class ProductListComponent {
page = signal(1);
category = signal('books');
products = httpResource<Product[]>(
() => ({
url: '/api/products',
params: {
category: this.category(),
page: this.page(),
pageSize: 20,
},
}),
{ defaultValue: [] },
);
}The first request goes to /api/products?category=books&page=1&pageSize=20. Because the request function reads category and page, changing either signal triggers a new request.
In a record, each value must be a string, number or boolean, or a read-only array of those. An array produces a repeated key: { tag: ['a', 'b'] } becomes ?tag=a&tag=b. A value of undefined is not allowed. If a filter is optional, add it to the object only when it has a value.
import { signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
const minPrice = signal<number | null>(null);
export const filtered = httpResource<unknown[]>(() => {
const params: Record<string, string | number> = { sort: 'price' };
const min = minPrice();
if (min !== null) {
params['minPrice'] = min;
}
return { url: '/api/products', params };
});If you already work with HttpParams elsewhere in your code, you can pass an HttpParams instance instead of a record.
Headers
Headers work the same way as params: either an HttpHeaders object or a record of strings and string arrays.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
@Component({
selector: 'app-report',
template: `<pre>{{ report.value() | json }}</pre>`,
})
export class ReportComponent {
locale = signal('en-GB');
report = httpResource<unknown>(() => ({
url: '/api/report',
headers: {
'Accept-Language': this.locale(),
'X-Client': 'web',
},
}));
}The json pipe in this template needs JsonPipe in the component's imports. Add it before you run the example. With that import in place, changing locale sends a new request with the new Accept-Language header.
Do not set authentication tokens here. A token that every request needs belongs in an interceptor, which a later chapter covers. Setting it per resource is repetitive and easy to forget.
Method and body
By default httpResource sends a GET request. You can set method to another verb and supply a body. The usual reason is a read-only endpoint that takes a complex query, where a long filter object does not fit in a URL.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface SearchFilter {
text: string;
tags: string[];
}
interface SearchHit {
id: number;
title: string;
}
@Component({
selector: 'app-advanced-search',
template: `
<input (input)="text.set($any($event.target).value)" />
<ul>
@for (hit of hits.value(); track hit.id) {
<li>{{ hit.title }}</li>
}
</ul>
`,
})
export class AdvancedSearchComponent {
text = signal('');
tags = signal<string[]>(['angular']);
hits = httpResource<SearchHit[]>(
() => {
const text = this.text();
if (!text) {
return undefined;
}
const body: SearchFilter = { text, tags: this.tags() };
return { url: '/api/search', method: 'POST', body };
},
{ defaultValue: [] },
);
}HttpClient serializes a plain object or array body as JSON and sets the Content-Type header for you. The request function returns undefined for an empty query, so nothing is sent until the user types.
The request function is evaluated each time a signal it reads changes. That means a POST request is sent again whenever text or tags changes. This is acceptable for a search that has no side effects on the server. It is the wrong behavior for an endpoint that creates or modifies data, and the last section of this chapter returns to that point.
How the request function is evaluated
The request function acts like a computed. Angular runs it, records which signals it read, and runs it again when any of them changes. Each run produces a request description, and Angular sends the request that the latest description names.
Two consequences follow:
- Only signals read inside the request function are tracked. A plain variable, or a signal read in a different function, does not trigger a request when it changes.
- Params, headers, method and body all take part in tracking. A change to any of them cancels the pending request and sends a new one.
Common errors
- A param stays stale. You copied a signal's value into a field once, for example
const page = this.page();in the constructor. Read the signal inside the request function instead, asthis.page(). - Type error on
params. A value ofundefined,null, an object or aDateis rejected. Convert it first, for exampledate.toISOString(), or leave the key out. - Duplicate requests for the same data. Two components each declare their own resource for the same URL. Each resource sends its own request. Share one resource through a service, or lift the declaration to a common parent.
- A body is ignored on GET. Browsers do not send a body with GET, and
HttpClientleaves it out. If an API expects a body, check whether it supports POST for reads. - Missing
HttpClientprovider. WithoutprovideHttpClient()the resource throws an error about a missingHttpClient.
When to stop using the request object
The method and body fields exist so that reads with unusual shapes still work. They are not an invitation to model every request as a resource. Use httpResource when the request answers the question "what data should this view show right now?". Use HttpClient when the request answers "do this action now". The remaining sections of the tutorial return to this boundary.
Exercise
A component declares results = httpResource<Item[]>(() => ({ url: '/api/items', params: { q: this.q(), owner: this.owner() } })), where owner is a signal<string | undefined>(undefined). TypeScript rejects the code. What is wrong, and how do you fix it so that owner is only sent when it has a value?
Show answer
A params record cannot contain undefined values, and owner() can return undefined. Build the params object inside the request function, add owner only when this.owner() returns a value, and return { url: '/api/items', params }. Because both signals are still read inside the request function, a change to either one triggers a new request.
Exercise
You write const lang = this.lang(); in the component constructor and then use headers: { 'Accept-Language': lang } in the request function. The user changes the language, but the resource never re-fetches. Why?
Show answer
The signal was read once, outside the request function, so Angular does not track it. The header value is a fixed string captured at construction time. Read this.lang() inside the request function so the resource depends on the signal.