Sub topic 2
Creating, Updating and Deleting Resources
This chapter assumes you already have a TodoService that injects HttpClient and makes typed GET requests. You should also know RxJS pipe and Angular signals.
Mutation Requests
post, put, patch and delete work like get. They take a URL, and every method except delete also takes a body. Each one returns a cold Observable, so nothing is sent until something subscribes. A forgotten subscribe() is the most common reason a save "does nothing".
| Method | Body | Typical use |
|---|---|---|
| `post<T>(url, body)` | New resource | Create |
| `put<T>(url, body)` | Full resource | Replace |
| `patch<T>(url, body)` | Changed fields only | Partial update |
| `delete<T>(url)` | None | Remove |
Query Parameters and Headers
HttpParams and HttpHeaders are immutable. set() returns a new instance, so you have to chain the calls or reassign the result.
// todo.service.ts (additions)
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable, catchError, retry, throwError } 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';
search(term: string, page: number): Observable<Todo[]> {
const params = new HttpParams().set('q', term).set('page', page);
const headers = new HttpHeaders().set('Accept-Language', 'en');
return this.http.get<Todo[]>(this.baseUrl, { params, headers });
}
toggle(todo: Todo): Observable<Todo> {
return this.http.patch<Todo>(`${this.baseUrl}/${todo.id}`, { completed: !todo.completed });
}
getTodoSafely(id: number): Observable<Todo> {
return this.http.get<Todo>(`${this.baseUrl}/${id}`).pipe(
retry(2),
catchError((error: HttpErrorResponse) => {
if (error.status === 0) {
console.error('Network error:', error.error);
} else {
console.error(`Server returned ${error.status}:`, error.error);
}
return throwError(() => new Error('Could not load the todo.'));
})
);
}
}Handling Errors and Retrying
A failed request emits an HttpErrorResponse. A status of 0 means the request never got a response, for example because the network was down or CORS blocked it. Any other status is the code the server returned. retry(2) resubscribes up to two more times, and each resubscription sends the request again.
Showing Data in Components
toSignal subscribes for you and unsubscribes when the component is destroyed.
// todo-list.component.ts
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { TodoService } from './todo.service';
@Component({
selector: 'app-todo-list',
template: `
<ul>
@for (todo of todos(); track todo.id) {
<li>{{ todo.title }}</li>
} @empty {
<li>No todos yet.</li>
}
</ul>
`
})
export class TodoListComponent {
private readonly todoService = inject(TodoService);
readonly todos = toSignal(this.todoService.search('', 1), { initialValue: [] });
}If you prefer Observables in templates, todos$ | async gives the same automatic cleanup.
Exercise
You write params.set('page', 2) on its own line and then pass params to get. The request has no page parameter. Why?
Show answer
HttpParams is immutable, so set() returns a new instance and leaves the original unchanged. Reassign the result (params = params.set('page', 2)) or chain the calls.
Exercise
Why might calling toggle(todo) in a click handler leave the server unchanged?
Show answer
The Observable is cold. Without a subscribe() call, or toSignal or the async pipe, the PATCH request is never sent.