Angular — HTTP Client
Service Pattern
// user.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class UserService {
private http = inject(HttpClient);
private apiUrl = '/api/users';
getUsers(): Observable<any[]> {
return this.http.get<any[]>(this.apiUrl);
}
getUser(id: number): Observable<any> {
return this.http.get<any>(`${this.apiUrl}/${id}`);
}
createUser(user: any): Observable<any> {
return this.http.post(this.apiUrl, user);
}
updateUser(id: number, user: any): Observable<any> {
return this.http.put(`${this.apiUrl}/${id}`, user);
}
deleteUser(id: number): Observable<any> {
return this.http.delete(`${this.apiUrl}/${id}`);
}
}
Headers and Options
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
});
this.http.get('/api/users', { headers });
Interceptors
// auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = localStorage.getItem('token');
if (token) {
const cloned = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`)
});
return next(cloned);
}
return next(req);
};
Mini Practice
- Create an HTTP service
- Add headers to requests
- Create an interceptor
- Handle authentication
Up Next
Continue with Observables — working with RxJS.
Related Topics
Frequently Asked Questions about HTTP Client
What is HTTP Client in Angular?
HTTP Client is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn HTTP Client?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn HTTP Client.
Why is HTTP Client important in Angular?
HTTP Client is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.