Sub topic 4
Fetching Typed Data with GET
This chapter assumes you know TypeScript interfaces and generics, and that you have registered HttpClient with provideHttpClient and injected it into a TodoService, as the previous chapters showed. It also assumes you know basic RxJS: what subscribe does and how pipe chains operators.
A GET request is the most common call an Angular app makes. The method signature looks simple, but it hides details that cause real bugs. A request does not run until something subscribes. Each subscription sends a new request. The type you pass as a generic is never checked against the data at runtime. This chapter covers each of these, plus how to reshape responses that don't match your models.
The Shape of a Typed GET
HttpClient.get takes a URL and an optional options object. When you pass a type argument, the returned Observable emits values of that type:
// todo.service.ts (excerpt)
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface Todo {
id: number;
title: string;
completed: boolean;
}
@Injectable({ providedIn: 'root' })
export class TodoService {
private readonly http = inject(HttpClient);
private readonly baseUrl = '/api/todos';
getTodo(id: number): Observable<Todo> {
return this.http.get<Todo>(`${this.baseUrl}/${id}`);
}
getAllTodos(): Observable<Todo[]> {
return this.http.get<Todo[]>(this.baseUrl);
}
}By default, get asks for JSON. It parses the response body with JSON.parse and emits the parsed value. If you leave out the type argument, you get Observable<Object>, which is awkward to work with. Always supply a type.
What the generic actually does
The type argument is a compile-time assertion. It is not validation. http.get<Todo> tells TypeScript "trust me, this will be a Todo." Angular does not inspect the JSON. If the server returns { "todo_id": 5, "name": "Buy milk" }, your code still receives that object typed as Todo. todo.title is undefined, and the compiler never warns you.
Lazy, Cold, and Single-Valued
The Observable returned by get has three properties that matter in practice.
| Property | Meaning | Practical consequence |
|---|---|---|
| Lazy | Nothing happens until `subscribe` is called | Calling `getTodo(1)` alone sends no request |
| Cold | Each subscriber triggers its own execution | Two subscriptions mean two HTTP requests |
| Single-valued | Emits one value (the body), then completes | No need to unsubscribe after it completes; operators like `take(1)` are redundant |
The following diagram shows the lifecycle of a single subscription.
Common error: forgetting to subscribe
This method looks correct, but it never contacts the server:
refresh(): void {
this.todoService.getAllTodos(); // Observable created and thrown away
}Something must subscribe: your own subscribe call, the async pipe, or toSignal. A later chapter covers the last two. The same rule applies to POST and DELETE. A "fire and forget" mutation that is never subscribed to is never sent.
Common error: accidental duplicate requests
Because the Observable is cold, each subscriber gets its own request:
const todos$ = this.todoService.getAllTodos();
todos$.subscribe(list => console.log('count', list.length));
todos$.subscribe(list => console.log('first', list[0]));
// The Network tab shows two GET /api/todos requestsThis often happens in templates that use the async pipe on the same Observable in two places. To share one response among several subscribers, use shareReplay:
import { shareReplay } from 'rxjs';
const todos$ = this.todoService.getAllTodos().pipe(
shareReplay({ bufferSize: 1, refCount: true })
);bufferSize: 1 replays the last value to late subscribers. With refCount: true, the shared subscription is dropped when the subscriber count falls to zero. If you put a shareReplay Observable in a root-scoped service property, it works as a simple cache that lives as long as the app. That can be what you want, but it also means stale data is never refetched unless you rebuild the Observable.
Reshaping Responses with map
Real APIs rarely return exactly the shape your components want. Two cases are very common: envelope objects and values that JSON cannot represent, such as dates.
Unwrapping an envelope
Many APIs wrap results in metadata:
{ "data": [{ "id": 1, "title": "Write tests", "completed": false }], "total": 42 }Type the raw response honestly, then use map to extract what callers need. Callers then never see the envelope:
import { map } from 'rxjs';
interface ListEnvelope<T> {
data: T[];
total: number;
}
// Inside TodoService
getTodoList(): Observable<Todo[]> {
return this.http
.get<ListEnvelope<Todo>>(this.baseUrl)
.pipe(map(envelope => envelope.data));
}Converting dates
JSON has no date type. A field like "dueDate": "2026-12-01T09:00:00Z" arrives as a string. Typing it as Date in your interface is a classic error: TypeScript allows calls like todo.dueDate.getTime(), which then throw at runtime because strings have no getTime method.
Keep one interface for the wire format and one for your domain model:
import { map } from 'rxjs';
interface TodoDto {
id: number;
title: string;
completed: boolean;
dueDate: string | null;
}
export interface DatedTodo {
id: number;
title: string;
completed: boolean;
dueDate: Date | null;
}
function toDatedTodo(dto: TodoDto): DatedTodo {
return {
...dto,
dueDate: dto.dueDate ? new Date(dto.dueDate) : null
};
}
// Inside TodoService
getDatedTodos(): Observable<DatedTodo[]> {
return this.http
.get<TodoDto[]>(this.baseUrl)
.pipe(map(dtos => dtos.map(toDatedTodo)));
}Do this mapping in the service. Components then work only with the domain type, and a backend format change touches one function.
Validating at the Boundary
The response comes from outside your app, across a trust boundary. If you need a guarantee that it matches your types, check it at runtime. A hand-written type guard is enough for small models:
import { map } from 'rxjs';
function isTodo(value: unknown): value is Todo {
if (typeof value !== 'object' || value === null) {
return false;
}
const v = value as Record<string, unknown>;
return (
typeof v['id'] === 'number' &&
typeof v['title'] === 'string' &&
typeof v['completed'] === 'boolean'
);
}
// Inside TodoService
getCheckedTodo(id: number): Observable<Todo> {
return this.http.get<unknown>(`${this.baseUrl}/${id}`).pipe(
map(body => {
if (!isTodo(body)) {
throw new Error(`Unexpected todo payload for id ${id}`);
}
return body;
})
);
}Typing the request as unknown forces you to narrow the value before using it. Throwing inside map turns the bad payload into an error notification, which subscribers handle like any other failure. The chapter on error handling covers how to catch it.
For larger APIs, a schema library such as Zod lets you declare a schema once and infer the TypeScript type from it, so the type and the check stay in sync. Whether validation is worth the cost depends on how much you trust and control the backend.
| Situation | Reasonable choice |
|---|---|
| Same team owns a typed backend and generates client types | Generic only |
| Third-party or public API | Runtime validation |
| Payload drives money, permissions, or persistence | Runtime validation |
| Prototype or internal tool | Generic only, add checks where bugs appear |
URLs and Edge Cases
A few details trip people up with GET requests:
- Relative URLs such as
/api/todosresolve against the page's origin. In development, a proxy configuration usually forwards/apito the backend. Absolute URLs to another origin require the server to send CORS headers. - Building URLs by concatenation is fine for path segments you control, such as a numeric
id. For user-supplied text, either encode it withencodeURIComponentor pass it as a query parameter. The next chapter coversHttpParams, which encodes values for you. - Empty bodies. If an endpoint returns
204 No Contentor an empty200for a GET, the emitted value isnull. Type it asTodo | nullif the API can do that. - Non-JSON bodies. If the server returns plain text or HTML (for example, a login page from a misconfigured proxy), JSON parsing fails and the Observable errors even though the status is 200. Reading text or binary data deliberately requires the
responseTypeoption, covered later. - Unsubscribing early while a request is in flight cancels it. The browser aborts the request. This is useful, and a later chapter builds on it with
switchMap.
Exercises
Exercise
A component calls this.todoService.getAllTodos() in ngOnInit and stores the result in a property used twice in the template with the async pipe. How many GET requests are sent, and how would you reduce it to one?
Show answer
Two requests, because the Observable is cold and each async pipe subscribes separately. Pipe the Observable through shareReplay({ bufferSize: 1, refCount: true }) before storing it, or subscribe once with a single async pipe using @if (todos$ | async; as todos) and reuse the todos variable.
Exercise
An interface declares createdAt: Date, and the code calls todo.createdAt.toLocaleDateString(). It compiles but throws at runtime. Why, and what is the fix?
Show answer
JSON has no date type, so createdAt arrives as a string. The generic on http.get only asserts the type and never converts values. Declare a DTO interface with createdAt: string and convert it with map in the service, for example createdAt: new Date(dto.createdAt), returning a domain type that really holds a Date.
Exercise
Write a service method getTodoTitles() that calls GET /api/todos, which returns { "data": Todo[], "total": number }, and emits only an array of titles.
Show answer
getTodoTitles(): Observable<string[]> { return this.http.get<{ data: Todo[]; total: number }>(this.baseUrl).pipe(map(res => res.data.map(t => t.title))); } with map imported from 'rxjs'.