Angular HTTP - Quick Reference
Deep Knowledge: Use mcp__documentation__fetch_docs with technology: angular, topic: http for comprehensive documentation.
HttpClient Setup
// app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './core/interceptors/auth.interceptor';
import { errorInterceptor } from './core/interceptors/error.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([authInterceptor, errorInterceptor])),
]
};
Functional Interceptors (Angular 15+)
// Auth interceptor
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).getToken();
if (token) {
req = req.clone({
setHeaders: { Authorization: `Bearer ${token}` },
});
}
return next(req);
};
// Error interceptor
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
inject(Router).navigate(['/login']);
}
return throwError(() => error);
})
);
};
// Loading interceptor
export const loadingInterceptor: HttpInterceptorFn = (req, next) => {
const loading = inject(LoadingService);
loading.show();
return next(req).pipe(finalize(() => loading.hide()));
};
Service Pattern with Error Handling
@Injectable({ providedIn: 'root' })
export class UserService {
private http = inject(HttpClient);
private baseUrl = '/api/users';
getUsers(): Observable<User[]> {
return this.http.get<User[]>(this.baseUrl).pipe(
retry({ count: 2, delay: 1000 }),
catchError(this.handleError),
);
}
create(user: CreateUserDto): Observable<User> {
return this.http.post<User>(this.baseUrl, user).pipe(
catchError(this.handleError),
);
}
private handleError(error: HttpErrorResponse): Observable<never> {
let message = 'An error occurred';
if (error.status === 0) {
message = 'Network error';
} else if (error.status === 404) {
message = 'Resource not found';
}
return throwError(() => new Error(message));
}
}
Typed Responses
// With observe: 'response' for full response
getWithHeaders(): Observable<HttpResponse<User[]>> {
return this.http.get<User[]>(this.baseUrl, { observe: 'response' });
}
// With params
search(query: string, page: number): Observable<PaginatedResult<User>> {
const params = new HttpParams()
.set('q', query)
.set('page', page.toString());
return this.http.get<PaginatedResult<User>>(this.baseUrl, { params });
}
Anti-Patterns
| Anti-Pattern |
Why It's Bad |
Correct Approach |
| Class-based interceptors |
Verbose, deprecated |
Use functional HttpInterceptorFn |
| Not typing responses |
No compile-time checks |
Use http.get<Type>() |
| Subscribing in services |
Tight coupling |
Return observables, subscribe in components |
| No error handling |
Silent failures |
Use catchError in service |
Quick Troubleshooting
| Issue |
Likely Cause |
Solution |
| HTTP call not firing |
Forgot to subscribe |
Subscribe to the observable |
| Interceptor not running |
Not in providers |
Add to withInterceptors() |
| CORS error |
Backend config |
Configure CORS on server |
| Wrong content type |
Missing header |
HttpClient sets JSON by default |
1---2name: angular-http3description: |4 Angular HttpClient with interceptors, error handling, retry, and caching patterns.5 Covers functional interceptors and typed responses.67 USE WHEN: user mentions "HttpClient", "Angular HTTP", "interceptors", "API calls",8 "Angular REST", "HTTP error handling", "auth interceptor"910 DO NOT USE FOR: Axios - use `axios` skill, Fetch API directly,11 backend HTTP frameworks12allowed-tools: Read, Grep, Glob, Write, Edit13metadata:14 source: https://skillmd.com/skills/claude-dev-suite/angular-http15---1617# Angular HTTP - Quick Reference1819> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `angular`, topic: `http` for comprehensive documentation.2021## HttpClient Setup2223```typescript24// app.config.ts25import { provideHttpClient, withInterceptors } from '@angular/common/http';26import { authInterceptor } from './core/interceptors/auth.interceptor';27import { errorInterceptor } from './core/interceptors/error.interceptor';2829export const appConfig: ApplicationConfig = {30 providers: [31 provideHttpClient(withInterceptors([authInterceptor, errorInterceptor])),32 ]33};34```3536## Functional Interceptors (Angular 15+)3738```typescript39// Auth interceptor40import { HttpInterceptorFn } from '@angular/common/http';41import { inject } from '@angular/core';4243export const authInterceptor: HttpInterceptorFn = (req, next) => {44 const token = inject(AuthService).getToken();45 if (token) {46 req = req.clone({47 setHeaders: { Authorization: `Bearer ${token}` },48 });49 }50 return next(req);51};5253// Error interceptor54export const errorInterceptor: HttpInterceptorFn = (req, next) => {55 return next(req).pipe(56 catchError((error: HttpErrorResponse) => {57 if (error.status === 401) {58 inject(Router).navigate(['/login']);59 }60 return throwError(() => error);61 })62 );63};6465// Loading interceptor66export const loadingInterceptor: HttpInterceptorFn = (req, next) => {67 const loading = inject(LoadingService);68 loading.show();69 return next(req).pipe(finalize(() => loading.hide()));70};71```7273## Service Pattern with Error Handling7475```typescript76@Injectable({ providedIn: 'root' })77export class UserService {78 private http = inject(HttpClient);79 private baseUrl = '/api/users';8081 getUsers(): Observable<User[]> {82 return this.http.get<User[]>(this.baseUrl).pipe(83 retry({ count: 2, delay: 1000 }),84 catchError(this.handleError),85 );86 }8788 create(user: CreateUserDto): Observable<User> {89 return this.http.post<User>(this.baseUrl, user).pipe(90 catchError(this.handleError),91 );92 }9394 private handleError(error: HttpErrorResponse): Observable<never> {95 let message = 'An error occurred';96 if (error.status === 0) {97 message = 'Network error';98 } else if (error.status === 404) {99 message = 'Resource not found';100 }101 return throwError(() => new Error(message));102 }103}104```105106## Typed Responses107108```typescript109// With observe: 'response' for full response110getWithHeaders(): Observable<HttpResponse<User[]>> {111 return this.http.get<User[]>(this.baseUrl, { observe: 'response' });112}113114// With params115search(query: string, page: number): Observable<PaginatedResult<User>> {116 const params = new HttpParams()117 .set('q', query)118 .set('page', page.toString());119 return this.http.get<PaginatedResult<User>>(this.baseUrl, { params });120}121```122123## Anti-Patterns124125| Anti-Pattern | Why It's Bad | Correct Approach |126|--------------|--------------|------------------|127| Class-based interceptors | Verbose, deprecated | Use functional `HttpInterceptorFn` |128| Not typing responses | No compile-time checks | Use `http.get<Type>()` |129| Subscribing in services | Tight coupling | Return observables, subscribe in components |130| No error handling | Silent failures | Use `catchError` in service |131132## Quick Troubleshooting133134| Issue | Likely Cause | Solution |135|-------|--------------|----------|136| HTTP call not firing | Forgot to subscribe | Subscribe to the observable |137| Interceptor not running | Not in providers | Add to `withInterceptors()` |138| CORS error | Backend config | Configure CORS on server |139| Wrong content type | Missing header | HttpClient sets JSON by default |