Sub topic 10
Parsing and validating responses
This chapter assumes you can declare an httpResource and read its value(), status() and error() signals. It also assumes you know TypeScript type narrowing.
Why a type argument is not validation
When you write httpResource<User>(...), the User type exists only at compile time. Angular does not check the JSON body against it. If the server returns { "id": "7" }, the resource still reports value() as a User. The mistake then shows up later, somewhere in your template or in a computed signal.
The parse option fixes this. It is a function that receives the raw response body and returns the value the resource should hold.
Using the parse option
parse runs after a successful response. Its input is the decoded JSON, which you should treat as unknown. Its return value becomes value().
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 does three jobs:
- It checks that the fields exist and have the expected types.
- It copies only the fields you want, so extra server fields do not leak into your state.
- It throws when the payload is wrong.
What happens when parse throws
A thrown error puts the resource into its error state. status() becomes 'error', and error() holds the thrown error. You handle it in the template exactly like a network failure.
| Situation | `status()` | `error()` |
|---|---|---|
| Valid response, parse succeeds | `resolved` | `undefined` |
| HTTP 500 | `error` | The HTTP error |
| HTTP 200, parse throws | `error` | Your thrown error |
Because of this, one @if (user.error()) block covers both transport and validation failures.
Transforming data, not only checking it
parse can also reshape the response. A common case is converting date strings into Date objects.
import { httpResource } from '@angular/common/http';
interface PostDto {
title: string;
publishedAt: string;
}
interface Post {
title: string;
publishedAt: Date;
}
function parsePost(raw: unknown): Post {
const dto = raw as PostDto;
const publishedAt = new Date(dto.publishedAt);
if (Number.isNaN(publishedAt.getTime())) {
throw new Error('Invalid publishedAt date');
}
return { title: dto.title, publishedAt };
}
export const post = httpResource<Post>(() => '/api/posts/1', {
parse: parsePost,
});Here the server type (PostDto) and the app type (Post) are separate. Components only see the clean Post.
Using a schema library
Hand-written checks get long. Libraries such as Zod expose a function that validates and returns typed data, which fits parse directly. The Zod schema's parse method throws on bad input, so it can be passed as the option.
import { httpResource } from '@angular/common/http';
import { z } from 'zod';
const UserSchema = z.object({
id: z.number(),
name: z.string(),
});
type User = z.infer<typeof UserSchema>;
export const user = httpResource<User>(() => '/api/users/1', {
parse: (raw) => UserSchema.parse(raw),
});This keeps the runtime check and the TypeScript type in one place, so they cannot drift apart.
Common errors
- Trusting the generic. Writing
httpResource<User>withoutparsegives no runtime safety. - Returning instead of throwing. If
parsereturnsnullfor bad data, the resource still counts as resolved. Throw to signal failure. - Using
parsefor side effects. It re-runs for each response. Keep it a pure function. - Expecting parse on a failed request. On an HTTP error status,
parseis never called.
Exercise
A server returns HTTP 200 with the body {"id": "5", "name": "Ana"}. Your resource is httpResource<User>(() => '/api/users/5') with no parse option, and User has id: number. What does value().id contain, and how would you make the resource enter its error state instead?
Show answer
value().id contains the string "5", because the generic is not checked at runtime. Add a parse option that checks typeof data.id === 'number' and throws an Error when it is not. The resource then has status 'error' and error() holds that Error.