Setting Up HttpClient
Angular's HttpClient provides a typed, Observable-based API for making HTTP requests.
Enabling HttpClient
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
};
Making a GET Request
import { Component, inject, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
interface User {
id: number;
name: string;
email: string;
}
@Component({
selector: 'app-user-list',
template: `
<p *ngFor="let user of users$ | async">{{ user.name }}</p>
`,
})
export class UserListComponent implements OnInit {
private http = inject(HttpClient);
users$!: Observable<User[]>;
ngOnInit(): void {
this.users$ = this.http.get<User[]>('/api/users');
}
}
HttpClient Methods
| Method | HTTP Verb | Example |
|---|---|---|
get<T>() |
GET | http.get<User[]>('/api/users') |
post<T>() |
POST | http.post<User>('/api/users', data) |
put<T>() |
PUT | http.put<User>('/api/users/1', data) |
patch<T>() |
PATCH | http.patch<User>('/api/users/1', data) |
delete<T>() |
DELETE | http.delete('/api/users/1') |
head() |
HEAD | http.head('/api/users') |
options() |
OPTIONS | http.options('/api/users') |
Cold Observables
HttpClient methods return cold Observables — nothing happens until you subscribe:
// No request is made yet
const users$ = this.http.get<User[]>('/api/users');
// Still no request
const users2$ = this.http.get<User[]>('/api/users');
// Request happens on subscribe
users$.subscribe(users => console.log(users));
// Each subscribe triggers a new request
users$.subscribe(users => console.log('Again:', users));
Type-Safe HTTP Requests
HttpClient is generic, providing compile-time type checking on response bodies.
Typing Responses
// Typed response
this.http.get<User[]>('/api/users').subscribe(users => {
users.forEach(user => console.log(user.name)); // string — type safe
});
// Single object
this.http.get<User>('/api/users/1').subscribe(user => {
console.log(user.email); // string — type safe
});
// Custom response shape
interface ApiResponse<T> {
data: T;
total: number;
page: number;
}
this.http.get<ApiResponse<User[]>>('/api/users').subscribe(response => {
console.log(response.data); // User[]
console.log(response.total); // number
console.log(response.page); // number
});
Error Handling with catchError
import { catchError, throwError } from 'rxjs';
this.http.get<User[]>('/api/users').pipe(
catchError(error => {
console.error('Failed to load users:', error.message);
return throwError(() => new Error('Failed to load users'));
})
).subscribe();
Using async Pipe in Templates
<!-- Subscribe and unsubscribe automatically -->
<div *ngIf="users$ | async as users">
<p *ngFor="let user of users">{{ user.name }}</p>
</div>
<!-- With loading state -->
<div *ngIf="users$ | async as users; else loading">
<p *ngFor="let user of users">{{ user.name }}</p>
</div>
<ng-template #loading><p>Loading...</p></ng-template>
Quiz
1. How do you enable HttpClient in Angular?
2. What type of Observable does HttpClient return?
3. How do you type an HTTP response?
Flashcards
Question
How do you enable HttpClient?
Click to reveal answer
Answer
provideHttpClient() in app.config.ts providers array.
Question
What type of Observable does HttpClient return?
Click to reveal answer
Answer
Cold Observable — request only fires on subscribe.
Question
How do you type HTTP responses?
Click to reveal answer
Answer
http.get<User[]>('/api/users') — generic type parameter.
Revision Notes
Key Takeaways
- 1. provideHttpClient() enables HttpClient
- 2. HttpClient returns cold Observables
- 3. Generic type parameters provide compile-time safety
- 4. Use async pipe for automatic subscription management
Interview Tips
- • Explain cold vs hot Observables in HTTP context
- • Be ready to describe type-safe HTTP requests
- • Mention the async pipe for template subscriptions
Cheat Sheet
HttpClient Basics Cheat Sheet
Enable:
provideHttpClient() // in app.config.ts
GET request:
this.http.get<User[]>('/api/users')
With async pipe:
<div *ngIf="users$ | async as users">
Type responses:
http.get<ApiResponse<User[]>>('/api/users')