📬 HTTP Configuration: Your App’s Mail System
Imagine your Angular app is a busy office. Every day, it needs to send letters (requests) to other offices (servers) and receive replies. The HTTP Client is your office’s mail system—and today, we’ll learn how to make it super smart!
🌟 The Big Picture
Think of HTTP requests like ordering pizza:
- Headers = Special instructions on your order (“Extra napkins please!”)
- Parameters = What you want (“Large pepperoni, no onions”)
- Response = The pizza arriving at your door
- Errors = “Sorry, we’re out of pepperoni!”
- Retry = Calling back: “Can you check again?”
- Interceptors = A helpful assistant who checks every order before it goes out
1️⃣ Request Headers
What Are Headers?
Headers are like sticky notes attached to your letter. They tell the mail carrier extra things like:
- “This is urgent!”
- “I’m allowed to access this building”
- “Please reply in English”
Simple Example
import { HttpClient, HttpHeaders } from '@angular/common/http';
// Create your sticky notes
const headers = new HttpHeaders({
'Authorization': 'Bearer my-secret-token',
'Content-Type': 'application/json'
});
// Attach them to your request
this.http.get('/api/data', { headers })
.subscribe(data => console.log(data));
Why Use Headers?
| Header | Purpose |
|---|---|
Authorization |
“Here’s my ID badge” |
Content-Type |
“My letter is written in JSON” |
Accept |
“Please reply in JSON” |
2️⃣ Request Parameters
What Are Parameters?
Parameters are like filling out an order form. Instead of saying “Give me everything,” you say exactly what you want.
Simple Example
import { HttpParams } from '@angular/common/http';
// Fill out your order form
const params = new HttpParams()
.set('page', '1')
.set('limit', '10')
.set('search', 'pizza');
// Send it!
this.http.get('/api/items', { params })
.subscribe(items => console.log(items));
This creates a URL like: /api/items?page=1&limit=10&search=pizza
Pro Tip 🚀
You can also pass params directly:
this.http.get('/api/items', {
params: { page: '1', limit: '10' }
});
3️⃣ Response Handling
The Pizza Arrives!
When your request comes back, you need to handle it properly. It’s like checking your pizza order:
this.http.get<User[]>('/api/users')
.subscribe({
next: (users) => {
// Pizza arrived! Enjoy!
console.log('Got users:', users);
},
error: (err) => {
// Something went wrong
console.error('Oops:', err);
},
complete: () => {
// Order is done
console.log('Request complete!');
}
});
Getting Full Response
Sometimes you need the whole package, not just the pizza:
this.http.get('/api/data', { observe: 'response' })
.subscribe(response => {
console.log('Status:', response.status);
console.log('Headers:', response.headers);
console.log('Body:', response.body);
});
4️⃣ HTTP Error Handling
When Things Go Wrong
graph TD A["Send Request"] --> B{Success?} B -->|Yes| C["Handle Data"] B -->|No| D{What Error?} D -->|404| E["Not Found"] D -->|401| F["Not Authorized"] D -->|500| G["Server Problem"] E --> H["Show Message"] F --> H G --> H
Catching Errors Like a Pro
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
this.http.get('/api/data')
.pipe(
catchError(error => {
if (error.status === 404) {
console.log('Page not found!');
} else if (error.status === 401) {
console.log('Please log in first!');
}
return throwError(() => error);
})
)
.subscribe(data => console.log(data));
Common Error Codes
| Code | Meaning | Like… |
|---|---|---|
| 400 | Bad Request | “Your order doesn’t make sense” |
| 401 | Unauthorized | “Show your ID first” |
| 404 | Not Found | “That pizza doesn’t exist” |
| 500 | Server Error | “Our oven broke!” |
5️⃣ Retry Requests
“Can You Try Again?”
Sometimes the pizza shop is busy. Instead of giving up, you try again!
import { retry, delay } from 'rxjs/operators';
this.http.get('/api/data')
.pipe(
retry(3) // Try 3 more times if it fails
)
.subscribe(data => console.log(data));
Smart Retry with Delay
import { retryWhen, delay, take } from 'rxjs/operators';
this.http.get('/api/data')
.pipe(
retryWhen(errors =>
errors.pipe(
delay(1000), // Wait 1 second
take(3) // Try 3 times max
)
)
)
.subscribe(data => console.log(data));
6️⃣ HTTP Interceptors
Your Helpful Office Assistant
Imagine having an assistant who:
- Adds your ID badge to every letter automatically
- Logs every letter sent and received
- Handles common problems before bothering you
That’s an Interceptor!
graph TD A["Your Request"] --> B["Interceptor"] B --> C["Add Auth Token"] C --> D["Log Request"] D --> E["Send to Server"] E --> F["Response"] F --> G["Interceptor"] G --> H["Log Response"] H --> I["Your App"]
Creating a Class-Based Interceptor
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler
} from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
// Clone the request and add auth header
const authReq = req.clone({
headers: req.headers.set(
'Authorization',
'Bearer my-token'
)
});
// Pass it along
return next.handle(authReq);
}
}
Register in App Module
import { HTTP_INTERCEPTORS } from '@angular/common/http';
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
]
7️⃣ Functional Interceptors
The Modern Way (Angular 15+)
Functional interceptors are simpler and easier to write!
import { HttpInterceptorFn } from '@angular/common/http';
export const authInterceptor: HttpInterceptorFn =
(req, next) => {
const authReq = req.clone({
headers: req.headers.set(
'Authorization',
'Bearer my-token'
)
});
return next(authReq);
};
Register in App Config
import { provideHttpClient, withInterceptors }
from '@angular/common/http';
export const appConfig = {
providers: [
provideHttpClient(
withInterceptors([authInterceptor])
)
]
};
Logging Interceptor Example
import { tap } from 'rxjs/operators';
export const loggingInterceptor: HttpInterceptorFn =
(req, next) => {
console.log('📤 Sending:', req.url);
return next(req).pipe(
tap(event => {
console.log('📥 Received:', event);
})
);
};
🎯 Quick Summary
| Concept | What It Does | Analogy |
|---|---|---|
| Headers | Add metadata to requests | Sticky notes on letters |
| Params | Filter/customize requests | Order form details |
| Response | Handle server replies | Opening your package |
| Errors | Deal with problems | “Order failed” handling |
| Retry | Try again on failure | Calling back the shop |
| Interceptors | Auto-process all requests | Office assistant |
| Functional | Modern, simpler interceptors | Smart assistant |
🏆 You Did It!
You now understand Angular’s HTTP configuration like a pro! Remember:
- Headers = Your request’s ID badge
- Params = What you’re asking for
- Response = What you get back
- Errors = Problems to handle gracefully
- Retry = Never give up too easily
- Interceptors = Your automatic helper
Go build amazing apps that talk to servers like pros! 🚀
