HttpClient: GET, POST, PUT and DELETE (CRUD)
Setup
HttpClient is Angular's tool for calling APIs. Register it once in app.config.ts.
typescript
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withFetch()), // withFetch uses the browser fetch API (good for SSR)
],
};
Practice API: Use
https://jsonplaceholder.typicode.com/posts (free fake API) or run your own with npx json-server db.json.
Model and CRUD Service
typescript
export interface Post {
id: number;
userId: number;
title: string;
body: string;
}
@Injectable({ providedIn: 'root' })
export class PostService {
private http = inject(HttpClient);
private url = 'https://jsonplaceholder.typicode.com/posts';
getAll(): Observable<Post[]> {
return this.http.get<Post[]>(this.url);
}
getById(id: number): Observable<Post> {
return this.http.get<Post>(`${this.url}/${id}`);
}
search(userId: number, page: number): Observable<Post[]> {
const params = new HttpParams().set('userId', userId).set('_page', page).set('_limit', 10);
return this.http.get<Post[]>(this.url, { params });
}
create(post: Omit<Post, 'id'>): Observable<Post> {
return this.http.post<Post>(this.url, post);
}
update(post: Post): Observable<Post> {
return this.http.put<Post>(`${this.url}/${post.id}`, post); // replace whole item
}
patch(id: number, changes: Partial<Post>): Observable<Post> {
return this.http.patch<Post>(`${this.url}/${id}`, changes); // change some fields
}
delete(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`);
}
}
| Method | Purpose | Body? |
|---|---|---|
GET | Read data | No |
POST | Create new item | Yes |
PUT | Replace an item | Yes |
PATCH | Change part of an item | Yes |
DELETE | Remove an item | No |
Show the List
typescript
@Component({
selector: 'app-posts',
imports: [],
templateUrl: './posts.html',
})
export class Posts {
private service = inject(PostService);
posts = toSignal(this.service.getAll(), { initialValue: [] as Post[] });
}
html
@for (p of posts(); track p.id) {
<article>
<h3>{{ p.title }}</h3>
<p>{{ p.body }}</p>
</article>
} @empty {
<p>Loading posts...</p>
}
Managing a List with Create, Update and Delete
typescript
export class PostsAdmin {
private service = inject(PostService);
posts = signal<Post[]>([]);
constructor() {
this.service.getAll().pipe(takeUntilDestroyed()).subscribe(list => this.posts.set(list));
}
add(title: string, body: string) {
this.service.create({ userId: 1, title, body }).subscribe(created => {
this.posts.update(list => [created, ...list]); // update local state
});
}
remove(id: number) {
this.service.delete(id).subscribe(() => {
this.posts.update(list => list.filter(p => p.id !== id));
});
}
rename(post: Post, title: string) {
this.service.patch(post.id, { title }).subscribe(saved => {
this.posts.update(list => list.map(p => (p.id === saved.id ? saved : p)));
});
}
}
Cold observables: An HTTP request is only sent when someone subscribes (or uses
async/toSignal). Subscribing twice sends two requests.
Headers, Response Details and Other Types
typescript
this.http.get<Post[]>(url, {
headers: new HttpHeaders({ 'X-Client': 'angular-app' }),
observe: 'response', // get status and headers too
});
this.http.get(url, { responseType: 'text' }); // plain text
this.http.get(url, { responseType: 'blob' }); // files, images
Keep URLs in one place: Put the base URL in an environment file or an
InjectionToken and use an interceptor (next lesson) to add it, instead of repeating it in every service.
Conclusion
HttpClient returns typed Observables. Wrap calls in a service, subscribe (or use toSignal) to send them, and update local state after create, update and delete.
Quick Summary: provideHttpClient() + service with get/post/put/patch/delete + toSignal or subscribe.

