Episode 24 of 27
HTTP Service
Make HTTP requests with Angular's HttpClient — GET, POST, PUT, DELETE and handling API responses.
HTTP Service
Angular's HttpClient module lets you make HTTP requests to APIs. It returns Observables that you subscribe to for the response.
Setting Up HttpClient
// app.module.ts
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule // ← Import this!
],
// ...
})
Creating an HTTP Service
// post.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
interface Post {
id?: number;
title: string;
body: string;
userId: number;
}
@Injectable({ providedIn: 'root' })
export class PostService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) {}
// GET all posts
getPosts(): Observable<Post[]> {
return this.http.get<Post[]>(this.apiUrl);
}
// GET single post
getPost(id: number): Observable<Post> {
return this.http.get<Post>(`${this.apiUrl}/${id}`);
}
// POST — create new
createPost(post: Post): Observable<Post> {
return this.http.post<Post>(this.apiUrl, post);
}
// PUT — update
updatePost(id: number, post: Post): Observable<Post> {
return this.http.put<Post>(`${this.apiUrl}/${id}`, post);
}
// DELETE
deletePost(id: number): Observable<any> {
return this.http.delete(`${this.apiUrl}/${id}`);
}
}
Using the Service in a Component
// post-list.component.ts
export class PostListComponent implements OnInit {
posts: Post[] = [];
isLoading = true;
error = '';
constructor(private postService: PostService) {}
ngOnInit(): void {
this.postService.getPosts().subscribe({
next: (data) => {
this.posts = data;
this.isLoading = false;
},
error: (err) => {
this.error = 'Failed to load posts.';
this.isLoading = false;
console.error(err);
}
});
}
deletePost(id: number): void {
this.postService.deletePost(id).subscribe(() => {
this.posts = this.posts.filter(p => p.id !== id);
});
}
}
The Template
<div *ngIf="isLoading">Loading posts...</div>
<div *ngIf="error" class="error">{{ error }}</div>
<div *ngFor="let post of posts" class="post-card">
<h3>{{ post.title | titlecase }}</h3>
<p>{{ post.body | truncate:100 }}</p>
<button (click)="deletePost(post.id)">Delete</button>
</div>
HTTP Methods Summary
| Method | Angular Code | Purpose |
|---|---|---|
| GET | http.get(url) | Fetch data |
| POST | http.post(url, body) | Create new data |
| PUT | http.put(url, body) | Update existing data |
| DELETE | http.delete(url) | Delete data |
Key Takeaways
- Import
HttpClientModulein your app module - Inject
HttpClientinto services — not components - HTTP methods return Observables — call
.subscribe()to execute - Handle both
next(success) anderror(failure) in the subscription - Use interfaces (
Post) for type-safe HTTP responses - Keep HTTP logic in services — components just subscribe