Sub topic 4
Fetching Typed Data with GET
This chapter assumes you already have provideHttpClient() in your application config and a TodoService that injects HttpClient, both set up in the previous chapters. You should also be comfortable with TypeScript generics and the RxJS pipe method.
The generic type parameter
HttpClient.get accepts a type argument that describes the shape of the response body. Angular parses the JSON for you and gives you an Observable of that type.
// todo.service.ts
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';
getTodos(): Observable<Todo[]> {
return this.http.get<Todo[]>(this.baseUrl);
}
getTodo(id: number): Observable<Todo> {
return this.http.get<Todo>(`${this.baseUrl}/${id}`);
}
}If you leave out the type argument, the result is Observable<Object>. You then lose autocompletion and type checking everywhere the data is used, so always pass the type.
Nothing happens until you subscribe
The Observable returned by get is cold. Calling getTodos() only builds a description of the request. The browser sends it when something subscribes, and each new subscription sends a new request.
const todos$ = this.todoService.getTodos(); // no request yet
todos$.subscribe(todos => console.log('First', todos)); // request 1
todos$.subscribe(todos => console.log('Second', todos)); // request 2The Observable emits one value, the parsed body, and then completes. Because it completes by itself, a single HTTP call does not leak a subscription the way a long-lived stream would.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Forgetting to subscribe | No request appears in the Network tab | Subscribe, or use the async pipe or `toSignal` |
| Subscribing in several places | Duplicate requests | Subscribe once, or share the result |
| Reading the value right after `subscribe` | Variable is still `undefined` | Use the value inside the callback |
| Expecting `Date` objects | JSON dates arrive as strings | Convert them with `map` |
Reshaping the response with map
The last row deserves an example. JSON has no date type, so date fields arrive as strings even if your interface says otherwise. Use a raw DTO type for the wire format and convert it in the service:
import { map } from 'rxjs';
interface TodoDto {
id: number;
title: string;
completed: boolean;
dueDate: string;
}
export interface DatedTodo {
id: number;
title: string;
completed: boolean;
dueDate: Date;
}
// Inside TodoService
getDatedTodos(): Observable<DatedTodo[]> {
return this.http.get<TodoDto[]>('/api/todos').pipe(
map(dtos => dtos.map(dto => ({ ...dto, dueDate: new Date(dto.dueDate) })))
);
}Components then receive real Date objects, and the conversion lives in one place. Query parameters, error handling, and display in templates each get their own chapter later.
Exercise
A component calls this.todoService.getTodo(5) in ngOnInit and stores the result in a field, but the browser's Network tab shows no request. Why, and what is the smallest fix?
Show answer
The returned Observable is cold, so no request is sent until something subscribes. The smallest fix is to subscribe, for example this.todoService.getTodo(5).subscribe(todo => this.todo = todo);. You could also bind the Observable with the async pipe or wrap it with toSignal.
Exercise
Your interface declares completed: boolean, but the API returns "completed": "yes". Does the TypeScript compiler or Angular report an error?
Show answer
Neither reports one. The generic on get<Todo> only tells the compiler what to assume. Angular parses the JSON without checking it, so completed holds the string "yes" at runtime. You need runtime validation or a mapping step to catch this.