HTTP Client & API Calls
The HttpClient service facilitates HTTP request communication with external API endpoints, returning RxJS Observables to handle responses.
1 HttpClient methods and interceptors
Key HTTP features in Angular include:
- Typed Responses: Define request structures using TypeScript interfaces:
http.get<User[]>(...). - HTTP Interceptors: Intercept and modify outgoing requests or incoming responses globally (e.g. adding authorization headers, logging requests, handling global errors).
2 HttpClient Integration Service
Let's check how to make API calls in a service:
TypeScript — API Service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface User {
id: number;
name: string;
email: string;
}
@Injectable({
providedIn: 'root'
})
export class ApiService {
private apiUrl = 'https://jsonplaceholder.typicode.com/users';
constructor(private http: HttpClient) {}
getUsers(): Observable {
return this.http.get(this.apiUrl);
}
createUser(user: Partial): Observable {
return this.http.post(this.apiUrl, user);
}
}
3 Code Challenge
Challenge: Write a component that injects the
ApiService above, calls getUsers(), and uses the async pipe in its HTML template to display the names of the fetched users.