Sub topic 5
Creating, Updating and Deleting Resources
This chapter assumes you have the TodoService from the previous chapters, with HttpClient injected and a typed getTodos method. You should also know what an HTTP method means and how to call subscribe on an Observable.
Reading data is half of most APIs. The other half is changing it. HttpClient has one method for each write verb: post, put, patch and delete. Each one returns a typed Observable, like get does.
The four write methods
| Method | Typical meaning | Body | Usual response |
|---|---|---|---|
| `post` | Create a new resource | Full new object | The created object, with its server-assigned `id` |
| `put` | Replace a resource | Full object | The replaced object |
| `patch` | Change some fields | Partial object | The updated object |
| `delete` | Remove a resource | None | Empty body (`204 No Content`) |
When you pass a plain object as the body, HttpClient serializes it to JSON and sets Content-Type: application/json for you. You don't need to call JSON.stringify.
Extending the data service
Here is the service with all four write operations. patchTodo takes Partial<Todo> because a PATCH body only needs the fields that change.
// 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';
addTodo(title: string): Observable<Todo> {
return this.http.post<Todo>(this.baseUrl, { title, completed: false });
}
updateTodo(todo: Todo): Observable<Todo> {
return this.http.put<Todo>(`${this.baseUrl}/${todo.id}`, todo);
}
patchTodo(id: number, changes: Partial<Todo>): Observable<Todo> {
return this.http.patch<Todo>(`${this.baseUrl}/${id}`, changes);
}
deleteTodo(id: number): Observable<void> {
return this.http.delete<void>(`${this.baseUrl}/${id}`);
}
}The generic type argument, such as <Todo>, describes what you expect the server to return. It does not describe the body you send. TypeScript does not check the response at runtime, so if the server sends a different shape, your code gets the wrong data without any error.
Nothing happens until you subscribe
HttpClient Observables are cold. Calling addTodo('Buy milk') builds the request but does not send it. The request goes out when something subscribes.
Here is a component that triggers writes from button clicks:
// todo-editor.component.ts
import { Component, inject, signal } from '@angular/core';
import { Todo, TodoService } from './todo.service';
@Component({
selector: 'app-todo-editor',
template: `
<button (click)="add()">Add</button>
@for (todo of todos(); track todo.id) {
<li>
{{ todo.title }}
<button (click)="toggle(todo)">Toggle</button>
<button (click)="remove(todo.id)">Delete</button>
</li>
}
`
})
export class TodoEditorComponent {
private readonly todoService = inject(TodoService);
readonly todos = signal<Todo[]>([]);
add(): void {
this.todoService.addTodo('Buy milk').subscribe(created =>
this.todos.update(list => [...list, created])
);
}
toggle(todo: Todo): void {
this.todoService
.patchTodo(todo.id, { completed: !todo.completed })
.subscribe(updated =>
this.todos.update(list => list.map(t => (t.id === updated.id ? updated : t)))
);
}
remove(id: number): void {
this.todoService.deleteTodo(id).subscribe(() =>
this.todos.update(list => list.filter(t => t.id !== id))
);
}
}The HttpClient Observable completes after one response, so these subscriptions clean themselves up and you don't need to unsubscribe manually.
Common mistakes
- Forgetting to subscribe. The method runs, nothing reaches the network, and the Network tab in DevTools stays empty.
- Using PUT for a partial update. PUT replaces the whole resource. If you send only
{ completed: true }, many servers cleartitle. Use PATCH for partial changes. - Typing DELETE with a body type. Most DELETE endpoints return no content. Use
<void>so callers don't try to read a result that isn't there. - Sending a body with DELETE.
deletehas no body parameter. If your API needs one, pass it in the options:this.http.delete(url, { body: payload }).
Exercise
A teammate writes this.todoService.updateTodo({ id: 5, completed: true } as Todo) to mark todo 5 done, and the todo's title disappears on the server. Why, and what should they call instead?
Show answer
updateTodo sends a PUT, which replaces the whole resource. The body has no title, so the server stores the todo without one. They should call this.todoService.patchTodo(5, { completed: true }) and subscribe to it, so that only the completed field is sent and changed.
Exercise
You call const req$ = this.todoService.addTodo('Read docs'); and never use req$ again. How many todos does the server create?
Show answer
None. HttpClient Observables are cold, so no request is sent until something subscribes to req$.