đŹ 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! đ
