Sub topic 10
Parsing and validating responses
This chapter assumes you can write an Angular component with signals, and that you have already declared a basic httpResource and read its value(), error() and isLoading() signals in a template. You should also know how a JSON response arrives over HTTP.
Why parsing matters
When you write httpResource<User>(...), the type argument is only a promise to the compiler. Angular does not check that the server's JSON matches User. If the API returns { "id": "7" } or null, TypeScript still treats value() as a User. The mistake then shows up later, far from the request, as a confusing undefined error in a template or a service.
The parse option moves that check to the boundary where data enters your app. It is a function that receives the raw response body and returns the value the resource should expose.
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
}
function parseUser(raw: unknown): User {
const data = raw as Partial<User> | null;
if (!data || typeof data.id !== 'number' || typeof data.name !== 'string') {
throw new Error('Unexpected user payload');
}
return { id: data.id, name: data.name };
}
export function createUserResource(id: () => number) {
return httpResource<User>(() => `/api/users/${id()}`, { parse: parseUser });
}The function takes unknown, so the compiler forces you to narrow it before use. It returns only the fields you name, so extra properties from the server are dropped. If it throws, the resource moves to its error state.
How parse fits into the request
Parsing happens after the HTTP response succeeds and before the value is published. The order matters when you debug.
Two consequences follow:
- A 404 or 500 never reaches
parse. Angular'sHttpClientalready turns those into errors. - A parse failure and a network failure look the same to the template, because both set
error(). Inspect the error object if you need to tell them apart.
What the error state looks like
When parse throws, the resource's status() becomes 'error', error() holds what you threw, and value() is not usable. In the Angular version this chapter is written against, reading value() while the resource is in the error state throws an error itself. You can guard against this with hasValue(), or by reading error() first in the template.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
}
function parseUser(raw: unknown): User {
const data = raw as Partial<User> | null;
if (!data || typeof data.id !== 'number' || typeof data.name !== 'string') {
throw new Error('Unexpected user payload');
}
return { id: data.id, name: data.name };
}
@Component({
selector: 'app-checked-user',
template: `
@if (user.isLoading()) {
<p>Loading…</p>
} @else if (user.error()) {
<p>Problem: {{ user.error()?.message }}</p>
} @else if (user.hasValue()) {
<p>{{ user.value().name }}</p>
}
`,
})
export class CheckedUserComponent {
userId = signal(1);
user = httpResource<User>(() => `/api/users/${this.userId()}`, {
parse: parseUser,
});
}The @else if chain checks the states in a fixed order. Loading comes first, then error, then a resolved value. Because the branches are exclusive, user.value() is only read when a value exists.
Transforming, not only validating
parse can change the shape of the data as well as check it. A common use is converting a date string into a Date, or renaming snake_case fields from an API.
import { httpResource } from '@angular/common/http';
interface Article {
id: number;
title: string;
publishedAt: Date;
}
function parseArticle(raw: unknown): Article {
const data = raw as {
id?: unknown;
title?: unknown;
published_at?: unknown;
} | null;
if (
!data ||
typeof data.id !== 'number' ||
typeof data.title !== 'string' ||
typeof data.published_at !== 'string'
) {
throw new Error('Unexpected article payload');
}
const publishedAt = new Date(data.published_at);
if (Number.isNaN(publishedAt.getTime())) {
throw new Error('Invalid published_at date');
}
return { id: data.id, title: data.title, publishedAt };
}
export function createArticleResource(id: () => number) {
return httpResource<Article>(() => `/api/articles/${id()}`, {
parse: parseArticle,
});
}Doing the conversion here means every consumer of the resource gets a real Date. No component has to remember to call new Date(...) on a string.
Using a schema library
Hand-written checks get long for large payloads. A schema library keeps the rules in one declarative place. Libraries such as Zod expose a function that takes unknown input, returns typed output, and throws on mismatch. That shape is exactly what parse expects.
import { httpResource } from '@angular/common/http';
import { z } from 'zod';
const ProductSchema = z.object({
id: z.number(),
title: z.string(),
price: z.number().nonnegative(),
});
type Product = z.infer<typeof ProductSchema>;
export function createProductResource(id: () => number) {
return httpResource<Product>(() => `/api/products/${id()}`, {
parse: ProductSchema.parse,
});
}This example needs npm install zod, and Zod is not part of Angular. The key point is the interface: any function from unknown to your type can be passed as parse. A single schema also gives you the TypeScript type through z.infer, so the runtime check and the compile-time type cannot drift apart.
Parse and defaultValue
parse and defaultValue solve different problems and work together. defaultValue sets what value() returns before any response has arrived or after a failure. parse shapes what comes back from the server.
import { httpResource } from '@angular/common/http';
interface Tag {
id: number;
label: string;
}
function parseTags(raw: unknown): Tag[] {
if (!Array.isArray(raw)) {
throw new Error('Expected an array of tags');
}
return raw.map((item) => {
const t = item as Partial<Tag>;
if (typeof t.id !== 'number' || typeof t.label !== 'string') {
throw new Error('Unexpected tag payload');
}
return { id: t.id, label: t.label };
});
}
export const tags = httpResource<Tag[]>(() => '/api/tags', {
parse: parseTags,
defaultValue: [],
});The array is validated element by element, so one malformed entry fails the whole response. That is usually what you want. If you would rather skip bad entries, filter inside parse and return only the good ones, but decide that on purpose, because it hides server bugs.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Trusting the generic type alone | Wrong data passes silently and fails later | Add a `parse` function |
| Typing the `parse` argument as the final type | The compiler cannot catch unchecked access | Accept `unknown` and narrow |
| Returning `undefined` from `parse` for bad data | The resource reports a resolved state with no useful value | Throw an error instead |
| Doing slow work in `parse` | It runs on every response and blocks the main thread | Keep it to checks and light mapping |
| Expecting `parse` to run on HTTP errors | It never does | Handle those through `error()` |
When to skip parse
Not every resource needs it. For an internal API you control, with shared types and tests, the generic type may be enough. Add parse when the data crosses a trust boundary: a third-party API, a service owned by another team, or a backend that changes without notice. Also add it when you need a transformation such as dates or renamed fields, because that work has to happen somewhere.
Testing a parser
A parse function is a plain function, so you can test it without Angular.
import { describe, it, expect } from 'vitest';
interface User {
id: number;
name: string;
}
function parseUser(raw: unknown): User {
const data = raw as Partial<User> | null;
if (!data || typeof data.id !== 'number' || typeof data.name !== 'string') {
throw new Error('Unexpected user payload');
}
return { id: data.id, name: data.name };
}
describe('parseUser', () => {
it('keeps only known fields', () => {
const result = parseUser({ id: 1, name: 'Ada', admin: true });
expect(result).toEqual({ id: 1, name: 'Ada' });
});
it('rejects a string id', () => {
expect(() => parseUser({ id: '1', name: 'Ada' })).toThrow();
});
it('rejects null', () => {
expect(() => parseUser(null)).toThrow();
});
});Cover at least one valid payload, one wrong type, and null. Those three cases catch most real bugs.
Exercise
A resource declared as httpResource<User>(() => '/api/users/1') receives { "id": "1", "name": "Ada" } from the server. What does value() hold, and how would you make the resource report an error instead?
Show answer
value() holds the object exactly as received, with id as the string "1", even though the type says number, because the generic argument is not checked at runtime. Add a parse option whose function accepts unknown, checks typeof data.id === 'number', and throws an error when the check fails. The resource then enters the error state and error() holds the thrown error.
Exercise
Write the parse function body for a resource that returns { "count": 3 } and must expose count as a number, rejecting any other shape.
Show answer
function parseCount(raw: unknown): { count: number } { const data = raw as { count?: unknown } | null; if (!data || typeof data.count !== 'number') { throw new Error('Unexpected count payload'); } return { count: data.count }; } Pass it with { parse: parseCount } as the second argument to httpResource.
Exercise
A server returns a 500 status for a resource that has a parse function. Does parse run? Why does it matter for error handling?
Show answer
No. A failing HTTP status becomes an error before parsing, so parse only sees successful bodies. Error handling therefore needs two paths in mind: HTTP failures and parse failures. Both appear in error(), so inspect the error if the template must tell them apart.