Sub topic 11
Loading and saving tasks over HTTP
This chapter assumes you have a Task interface, a service injected with inject(), and a basic grasp of signals. It also assumes you know that an Observable is a stream of values you subscribe to. The previous chapter covered Observables in more detail.
Registering HttpClient
HttpClient is Angular's service for making HTTP requests. It is only available for injection if you register it. The application config from the routing chapter already does this with provideHttpClient(). If you forget it, Angular throws a NullInjectorError for HttpClient the first time a service asks for it.
Wrapping requests in a service
Keep URLs and request details out of components. A small API service owns them and returns typed Observables:
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { Task } from './task';
@Injectable({ providedIn: 'root' })
export class TaskApi {
private readonly http = inject(HttpClient);
getTasks(): Observable<Task[]> {
return this.http.get<Task[]>('/api/tasks');
}
addTask(title: string): Observable<Task> {
return this.http.post<Task>('/api/tasks', { title });
}
}The /api/tasks URL is a placeholder for your backend. The type argument in get<Task[]> is a compile-time promise only. Angular does not check that the server's JSON matches Task, so a mismatched response fails later, at the point where you use it.
Nothing happens until you subscribe
Calling getTasks() does not send a request. It returns a cold Observable, which is a description of a request. The request is sent when something subscribes, and each subscription sends a separate request.
Subscribing and handling the result
A component can subscribe and put the result into a signal. This sketch also tracks an error message:
import { Component, inject, signal } from '@angular/core';
import { Task } from './task';
import { TaskApi } from './task.api';
@Component({
selector: 'app-remote-tasks',
template: `
@if (error()) {
<p role="alert">{{ error() }}</p>
}
<ul>
@for (task of tasks(); track task.id) {
<li>{{ task.title }}</li>
} @empty {
<li>No tasks yet.</li>
}
</ul>
`,
})
export class RemoteTasksComponent {
private readonly api = inject(TaskApi);
readonly tasks = signal<Task[]>([]);
readonly error = signal<string | null>(null);
constructor() {
this.api.getTasks().subscribe({
next: list => this.tasks.set(list),
error: () => this.error.set('Could not load tasks.'),
});
}
}Saving follows the same pattern. Subscribe to addTask(title), and in next append the task the server returned, using update(list => [...list, created]). Use the server's version because it carries the real id.
Angular completes HttpClient Observables after one response, so you do not need to unsubscribe from them.
Common errors
| Symptom | Likely cause |
|---|---|
| `NullInjectorError: No provider for HttpClient` | `provideHttpClient()` is missing from `app.config.ts`. |
| No request appears in the Network tab | Nothing subscribed to the Observable. |
| The same request fires twice | The Observable was subscribed to twice, for example from two places. |
| A 404 on `/api/tasks` in development | The dev server has no backend at that path. Add a proxy or point to a real URL. |
| An unhandled error in the console | The subscription has no `error` callback. |
Exercise
You call this.api.addTask('Buy milk') in a click handler, but the Network tab shows no POST request and no error. What is missing, and why does the code compile anyway?
Show answer
The call never subscribes. addTask returns a cold Observable, which only describes the request. It compiles because an unused Observable value is valid TypeScript. Adding .subscribe({ next: ..., error: ... }) sends the request.