π HTTP Client & RxJS
HttpClient, Observables, RxJS operators (map, switchMap, catchError), interceptors, and AsyncPipe.
Angular HttpClient Setup
Configure `provideHttpClient()` in standalone application config or import `HttpClientModule`.
app.config.ts
TypeScript
import { ApplicationConfig } from '@angular/core'; import { provideHttpClient, withInterceptors } from '@angular/common/http'; export const appConfig: ApplicationConfig = { providers: [provideHttpClient()] };
Making HTTP GET / POST Requests
HttpClient methods return RxJS `Observable` streams that emit responses when subscribed to.
data.service.ts
TypeScript
import { Injectable, inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, catchError, throwError } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DataService { private http = inject(HttpClient); private apiUrl = 'https://api.example.com/posts'; getPosts(): Observable<any[]> { return this.http.get<any[]>(this.apiUrl).pipe( catchError(err => { console.error('API Error:', err); return throwError(() => new Error('Failed to fetch posts')); }) ); } }
Essential RxJS Operators
RxJS operators transform, filter, and compose observable data streams.
| Operator | Category | Description |
|---|---|---|
| map | Transformation | Transforms emitted items by applying a function. |
| filter | Filtering | Emits values that pass a predicate condition. |
| switchMap | Transformation | Cancels previous pending HTTP requests when new emission occurs. |
| catchError | Error Handling | Catches errors on source observable to handle gracefully. |
| tap | Utility | Executes side-effects (logging) without modifying stream values. |
HTTP Interceptors
Interceptors globally modify HTTP requests (e.g. adding bearer auth headers) and responses.
auth.interceptor.ts
TypeScript
import { HttpInterceptorFn } from '@angular/common/http'; export const authInterceptor: HttpInterceptorFn = (req, next) => { const token = localStorage.getItem('token'); if (token) { const authReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); return next(authReq); } return next(req); };