Sub topic 11
Loading and saving tasks over HTTP
This chapter connects the task list to a backend. You will wrap HttpClient in a typed API service, load tasks when the list opens, save new tasks, and show loading and error states with signals.
It assumes you have the TaskService from the signals and services chapters, the provideHttpClient() call in app.config.ts from the routing chapter, and the basics of Observables from the RxJS chapter.
What HttpClient returns
HttpClient is Angular's service for HTTP requests. Each method (get, post, put, patch, delete) returns an Observable. Four properties of that Observable shape the code in this chapter:
- It is lazy. Calling
http.get(...)builds a description of a request. The request is sent only when something subscribes. - It is cold. Each subscription sends its own request. Subscribing twice sends two requests.
- It emits once and completes. For a normal JSON call you get one value, then a complete notification. You do not need to unsubscribe to avoid a leak, although unsubscribing before the response arrives cancels the request.
- It errors instead of throwing. A network failure or a 4xx/5xx status arrives through the error channel as an
HttpErrorResponse.
| Method | Typical use | Body |
|---|---|---|
| `get<T>(url)` | Read a resource or a list | None |
| `post<T>(url, body)` | Create a resource | Yes |
| `put<T>(url, body)` | Replace a resource | Yes |
| `patch<T>(url, body)` | Change part of a resource | Yes |
| `delete<T>(url)` | Remove a resource | None |
The API service
Keep raw HTTP calls out of components. A small service owns the URLs and the response types. Save this as task-api.ts:
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 URL /api/tasks is a placeholder. Any backend that answers GET /api/tasks with a JSON array of tasks, and POST /api/tasks with the created task including its id, will work.
The type argument in get<Task[]> is a promise to the compiler, not a check. Angular does not validate the JSON at runtime. If the server sends { "id": "7" }, your code still compiles and task.id is a string at runtime. When you do not control the backend, validate the data at this boundary with a schema library or a hand-written guard.
Observables do nothing until you subscribe
This is the most common HTTP mistake in Angular:
// Wrong: no request is ever sent.
this.api.addTask('Buy milk');
// Right: subscribing triggers the request.
this.api.addTask('Buy milk').subscribe();The service in the next section subscribes inside its own methods, so components never see the Observable. That also keeps the "no subscription, no request" trap in one place.
Connecting the API to the signal state
The signals you built earlier hold the data. The HTTP layer only decides when to write to them. Add three things to TaskService: a load() method, a create() method, and two signals for the request state, loading and error.
import { Injectable, computed, inject, signal } from '@angular/core';
import { Task } from './task';
import { TaskApi } from './task-api';
@Injectable({ providedIn: 'root' })
export class TaskService {
private readonly api = inject(TaskApi);
private readonly _tasks = signal<Task[]>([]);
private readonly _loading = signal(false);
private readonly _error = signal<string | null>(null);
private nextId = 1;
readonly tasks = this._tasks.asReadonly();
readonly loading = this._loading.asReadonly();
readonly error = this._error.asReadonly();
readonly remaining = computed(() => this._tasks().filter(t => !t.done).length);
load(): void {
this._loading.set(true);
this._error.set(null);
this.api.getTasks().subscribe({
next: tasks => {
this._tasks.set(tasks);
this._loading.set(false);
},
error: () => {
this._error.set('Could not load tasks.');
this._loading.set(false);
},
});
}
create(title: string): void {
this._error.set(null);
this.api.addTask(title).subscribe({
next: task => this._tasks.update(list => [...list, task]),
error: () => this._error.set('Could not save the task.'),
});
}
add(title: string): void {
this._tasks.update(list => [...list, { id: this.nextId++, title, done: false }]);
}
toggle(id: number): void {
this._tasks.update(list => list.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
}
remove(id: number): void {
this._tasks.update(list => list.filter(t => t.id !== id));
}
}Several choices here are deliberate:
- The server owns ids.
create()appends the task the server returns, so theidis the real one. The localadd()andnextIdstay for offline use and tests, but you should not mix both in one list, because local ids can collide with server ids. - State is replaced, not mutated.
setandupdatereceive new arrays, socomputedvalues and templates update correctly, as in earlier chapters. - Both outcomes reset the flag.
loadingreturns tofalseinnextand inerror. If you reset it in only one branch, the spinner stays on after a failure. toggleandremoveare still local. Persisting them needsput/patchanddeletecalls that follow the same pattern. The exercise at the end asks you to write one.
Showing the states in the component
Call load() once when the list component is created, and add the two new signals to the template. Update TaskListComponent like this:
import { Component, inject } from '@angular/core';
import { TaskService } from './task.service';
@Component({
selector: 'app-task-list',
template: `
@if (loading()) {
<p>Loading tasks...</p>
}
@if (error(); as message) {
<p role="alert">{{ message }}</p>
}
<ul>
@for (task of tasks(); track task.id) {
<li>
<input type="checkbox" [checked]="task.done" (change)="toggle(task.id)" />
<span [class.done]="task.done">{{ task.title }}</span>
<button type="button" (click)="remove(task.id)">Delete</button>
</li>
} @empty {
<li>No tasks yet.</li>
}
</ul>
<p>{{ remaining() }} remaining</p>
`,
})
export class TaskListComponent {
private readonly service = inject(TaskService);
readonly tasks = this.service.tasks;
readonly remaining = this.service.remaining;
readonly loading = this.service.loading;
readonly error = this.service.error;
constructor() {
this.service.load();
}
toggle(id: number): void {
this.service.toggle(id);
}
remove(id: number): void {
this.service.remove(id);
}
}In TaskFormComponent, change this.service.add(value) to this.service.create(value). The form resets right after the call, before the server answers. For a short form that is fine. If you want to keep the text on failure, reset the control only after a successful response, which means returning the Observable or a callback from create().
One more edge case: the @empty block shows "No tasks yet." during the first load, because the list is empty until the response arrives. If that flicker bothers you, wrap the list in @if (!loading()).
The request flow
Running against a backend during development
ng serve serves only your front end, so a request to /api/tasks goes to the dev server and returns 404. A proxy forwards /api calls to your backend and avoids CORS problems in development. Create proxy.conf.json in the project root:
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}Then start the server with ng serve --proxy-config proxy.conf.json. You can also set proxyConfig in the serve options of angular.json. The proxy applies only to the dev server. In production, the server that hosts the built files must route /api to the backend, or you must use the backend's full URL and configure CORS on it.
Common errors
- No request appears in the Network tab. You called an API method and never subscribed.
- Two identical requests. You subscribed twice, or two components both call
load(). - 404 on
/api/tasks. The proxy is not active. Restartng serveafter you create or edit the proxy file. NullInjectorError: No provider for HttpClient.provideHttpClient()is missing fromapp.config.ts, or from theTestBedconfiguration in a test.- The spinner never stops. One of the
nextorerrorpaths does not clearloading. - Duplicate keys or odd
@forbehavior. The list mixes local ids fromadd()with server ids fromcreate().
Exercise
A teammate writes this.api.addTask(title); in create() and reports that clicking Add does nothing, with no errors in the console and no entry in the Network tab. What is wrong, and what is the smallest fix?
Show answer
addTask returns a cold Observable, and a cold Observable sends no request until someone subscribes. The call is never subscribed, so no HTTP request is made and no error occurs. The fix is to subscribe, preferably with handlers: this.api.addTask(title).subscribe({ next: task => this._tasks.update(list => [...list, task]), error: () => this._error.set('Could not save the task.') }).
Exercise
Add a deleteTask(id: number): Observable<void> method to TaskApi that sends DELETE /api/tasks/{id}. Then change TaskService.remove so that it removes the task from the signal only after the server confirms, and sets the error message if the call fails.
Show answer
In TaskApi: deleteTask(id: number): Observable<void> { return this.http.delete<void>(/api/tasks/${id}); }. In TaskService: remove(id: number): void { this.api.deleteTask(id).subscribe({ next: () => this._tasks.update(list => list.filter(t => t.id !== id)), error: () => this._error.set('Could not delete the task.') }); }. Updating the signal inside next means the UI never shows a deletion the server rejected. The trade-off is a short delay before the row disappears. An optimistic version removes the row first and restores it in error.