Sub topic 5
Creating, Updating and Deleting Resources
This chapter assumes you already have HttpClient registered with provideHttpClient, a TodoService that injects it, and a working typed get call. You should also be comfortable subscribing to an Observable and know what HTTP methods and status codes mean. Here we add the methods that change data on the server: POST, PUT, PATCH and DELETE. We also cover the behaviors around them that cause the most bugs.
The Mutation Methods at a Glance
Every mutation method on HttpClient returns a cold Observable, just like get. The differences are in where the request body goes and in what the server usually sends back.
| Method | HttpClient signature | Typical purpose | Usual success response | Idempotent |
|---|---|---|---|---|
| POST | `post<T>(url, body, options?)` | Create a new resource | `201 Created` with the new resource | No |
| PUT | `put<T>(url, body, options?)` | Replace a resource completely | `200 OK` with the resource, or `204` | Yes |
| PATCH | `patch<T>(url, body, options?)` | Change some fields of a resource | `200 OK` with the resource | Not guaranteed |
| DELETE | `delete<T>(url, options?)` | Remove a resource | `204 No Content` or `200 OK` | Yes |
The type parameter T describes the response body, not the request body. HttpClient does not check the request body's type at all. If you want the compiler to check what you send, type the parameters of your service methods.
Extending the Data Service
Here is the full service with all four mutations. It builds on the Todo interface from earlier chapters.
// todo.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface Todo {
id: number;
title: string;
completed: boolean;
}
// What the client is allowed to send when creating a todo
export type NewTodo = Omit<Todo, 'id'>;
// What the client is allowed to send when patching a todo
export type TodoChanges = Partial<NewTodo>;
@Injectable({ providedIn: 'root' })
export class TodoService {
private readonly http = inject(HttpClient);
private readonly baseUrl = '/api/todos';
getTodos(page: number): Observable<Todo[]> {
const params = new HttpParams().set('page', page);
return this.http.get<Todo[]>(this.baseUrl, { params });
}
addTodo(title: string): Observable<Todo> {
const body: NewTodo = { title, completed: false };
return this.http.post<Todo>(this.baseUrl, body);
}
updateTodo(todo: Todo): Observable<Todo> {
return this.http.put<Todo>(`${this.baseUrl}/${todo.id}`, todo);
}
patchTodo(id: number, changes: TodoChanges): Observable<Todo> {
return this.http.patch<Todo>(`${this.baseUrl}/${id}`, changes);
}
deleteTodo(id: number): Observable<void> {
return this.http.delete<void>(`${this.baseUrl}/${id}`);
}
}Defining NewTodo and TodoChanges as derived types keeps them in sync with Todo. If you add a field to Todo, both derived types pick it up. Using Omit also stops callers from sending an id in a create request, because the server should assign it.
POST: Creating a Resource
The server creates the resource and normally returns it, including fields that only the server can fill in, such as id or timestamps. Always use the returned object in your local state rather than the object you sent. The returned object is the only one that has the real id.
Some APIs answer a POST with 201 Created, an empty body, and a Location header pointing at the new resource. In that case, declare the type as void and read the header using the observe: 'response' option, which a later chapter covers.
PUT Versus PATCH
PUT replaces the whole resource. Fields you leave out may be reset or deleted, depending on the server. So you should send the complete object, which is why updateTodo takes a full Todo.
PATCH sends only the fields that change. With patchTodo(5, { completed: true }), the body is {"completed":true}. Most JSON APIs treat this as a JSON Merge Patch: fields you send are overwritten, and fields you leave out stay as they are.
Some APIs expect the JSON Patch format (RFC 6902) instead, which is an array of operations such as [{ "op": "replace", "path": "/completed", "value": true }], sent with the application/json-patch+json content type. Check the API documentation. The next chapter shows how to set custom headers.
DELETE: Removing a Resource
delete has no body parameter, and its second argument is the options object. A 204 No Content response has no body, so the Observable emits null. Typing the call as delete<void> documents that you don't expect any data back.
A few APIs need a body on DELETE, for example to delete several items at once. HttpClient accepts one through the body option:
// Inside TodoService
deleteMany(ids: number[]): Observable<void> {
return this.http.delete<void>(`${this.baseUrl}/bulk`, { body: { ids } });
}Proxies and servers don't all accept a body on DELETE. Before you rely on one, check that every layer between the browser and the API passes it through.
How the Body Is Serialized
HttpClient looks at the value you pass as the body and picks the serialization and the Content-Type header itself, unless you set the header yourself.
| Body value | Sent as | Content-Type set automatically |
|---|---|---|
| Plain object or array | `JSON.stringify` output | `application/json` |
| `string` | The string as-is | `text/plain` |
| `number` or `boolean` | Converted to a string | `application/json` |
| `HttpParams` | URL-encoded `key=value&...` | `application/x-www-form-urlencoded;charset=UTF-8` |
| `FormData` | Multipart body | Set by the browser, including the boundary |
| `Blob` | Raw bytes | The blob's `type`, if any |
| `ArrayBuffer` | Raw bytes | None |
| `null` | No body | None |
Two problems come up often. If you pass a string that already contains JSON, for example the output of JSON.stringify(todo), it goes out as text/plain, and many servers reject it. Pass the object itself instead. And never set Content-Type by hand for FormData: the browser has to add the multipart boundary, and a hand-written header leaves it out.
// Inside TodoService: attaching a file to a todo
uploadAttachment(id: number, file: File): Observable<void> {
const form = new FormData();
form.append('file', file, file.name);
return this.http.post<void>(`${this.baseUrl}/${id}/attachments`, form);
}Nothing Happens Until You Subscribe
A mutation sends nothing until you subscribe to it, which makes it easy to break by accident. Calling this.todoService.deleteTodo(3) on its own only builds a description of a request.
This leads to two rules:
- Subscribe exactly once for each mutation you intend to send. If you subscribe twice, for example once to update the UI and once to log the result, the server gets two requests. With POST, that means two new records.
- Don't feed a mutation Observable to the
asyncpipe in a template. The template can re-subscribe whenever the view is recreated, and then the request runs again.
HttpClient Observables complete after a single response, so a subscription to a mutation cleans itself up. You don't need to unsubscribe for the sake of memory. You might still want to cancel a request that is in flight, which a later chapter covers.
Keeping the UI in Sync After a Mutation
After a mutation succeeds, the component's local copy of the data is out of date. You have three main options:
- Refetch: reload the list from the server. This is the simplest and always correct, but it costs an extra request.
- Merge the response: apply the returned object to local state. This is accurate and cheap.
- Optimistic update: change local state before the server answers, then roll back if the request fails. The UI feels instant, but you have to write the rollback code.
The component below uses a signal for local state. It merges server responses for create and toggle, and uses an optimistic update for delete.
// todo-editor.component.ts
import { Component, inject, signal } from '@angular/core';
import { Todo, TodoService } from './todo.service';
@Component({
selector: 'app-todo-editor',
template: `
<input #titleInput placeholder="New todo" />
<button
[disabled]="saving()"
(click)="add(titleInput.value); titleInput.value = ''">
Add
</button>
<ul>
@for (todo of todos(); track todo.id) {
<li>
<input
type="checkbox"
[checked]="todo.completed"
(change)="toggle(todo)" />
{{ todo.title }}
<button (click)="remove(todo)">Delete</button>
</li>
}
</ul>
`
})
export class TodoEditorComponent {
private readonly todoService = inject(TodoService);
readonly todos = signal<Todo[]>([]);
readonly saving = signal(false);
constructor() {
this.todoService.getTodos(1).subscribe(list => this.todos.set(list));
}
add(title: string): void {
const trimmed = title.trim();
if (!trimmed) return;
this.saving.set(true);
this.todoService.addTodo(trimmed).subscribe({
next: created => this.todos.update(list => [...list, created]),
complete: () => this.saving.set(false),
error: () => this.saving.set(false)
});
}
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(todo: Todo): void {
const previous = this.todos();
this.todos.update(list => list.filter(t => t.id !== todo.id));
this.todoService.deleteTodo(todo.id).subscribe({
error: () => this.todos.set(previous)
});
}
}Some details in this component matter:
adddisables the button while the POST is in flight. Because POST is not idempotent, a double click would otherwise create two todos.toggleswaps in the object the server returned, not a copy edited on the client. If the server changes other fields, such as anupdatedAttimestamp, the UI shows them.removesaves the previous array before it changes anything, so it can restore that array if the request fails. Signal updates create new arrays, which makes this snapshot safe to keep.
The error callbacks here only reset state. The chapter on error handling shows how to inspect HttpErrorResponse and tell the user what went wrong.
Edge Cases Worth Knowing
- Empty success bodies: a
200 OKwith an empty body and a JSON response type emitsnull. If you typed the call aspost<Todo>, your code receivesnullat runtime even though TypeScript saysTodo. Match the type to what the API really returns. - Non-JSON responses: if a mutation returns plain text such as
"OK", the default JSON parsing fails and you get an error even though the status was 2xx. SetresponseType: 'text'for those endpoints. - Response types are not checked at runtime:
post<Todo>is only a compile-time claim. If the server's shape can change, validate it, for example with a schema library inside amapoperator. undefinedfields disappear:JSON.stringifydrops properties whose value isundefined. In a PATCH,{ title: undefined }sends{}. To clear a field, sendnullexplicitly, if the API supports it.
Exercise
A teammate writes saveTitle(todo: Todo, title: string) { this.todoService.patchTodo(todo.id, { title }); this.todos.update(list => list.map(t => t.id === todo.id ? { ...t, title } : t)); }. The UI shows the new title, but after a page reload the old title comes back. Why, and what is the fix?
Show answer
patchTodo returns a cold Observable, and nobody subscribes to it, so no PATCH request is ever sent. Only the local signal changes. The fix is to subscribe: this.todoService.patchTodo(todo.id, { title }).subscribe(updated => this.todos.update(list => list.map(t => t.id === updated.id ? updated : t)));. If you want to keep the optimistic local update, add an error callback that restores the previous array.
Exercise
An edit form lets users change only a todo's title. The code calls updateTodo({ id: todo.id, title: newTitle } as Todo). What can go wrong, and which two approaches avoid it?
Show answer
updateTodo sends a PUT, which replaces the whole resource. Because completed is missing from the body, the server may reset it to false or reject the request. The as Todo cast hides this from the compiler. One fix is to call patchTodo(todo.id, { title: newTitle }), which sends only the changed field. The other is to send the full object with PUT: updateTodo({ ...todo, title: newTitle }).
Exercise
You need to send a todo to an endpoint and write this.http.post<Todo>(url, JSON.stringify(todo)). The server answers 415 Unsupported Media Type. What happened?
Show answer
Passing a string makes HttpClient send it as-is with Content-Type text/plain, so the server doesn't recognize the body as JSON. Pass the object directly, as in this.http.post<Todo>(url, todo). HttpClient then serializes it and sets Content-Type to application/json.