HTTP Interceptors mencegat dan memodifikasi HTTP request/response.
Functional Interceptor
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).getToken()
if (token) {
req = req.clone({
setHeaders: { Authorization: `Bearer ${token}` },
})
}
return next(req)
}
Registrasi
export const appConfig = {
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
],
}
Use Cases
- Auth token — tambah header Authorization
- Loading indicator — show/hide loading
- Error handling — handle 401/403 global
- Caching — cache response
Error Interceptor (Global Error Handling)
Salah satu use case paling sering: tangani error 401 (logout otomatis), tampilkan toast untuk 5xx, dsb — di satu tempat untuk seluruh app.
import { HttpInterceptorFn, HttpErrorResponse } from "@angular/common/http";
import { inject } from "@angular/core";
import { Router } from "@angular/router";
import { catchError, throwError } from "rxjs";
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
const router = inject(Router);
return next(req).pipe(
catchError((err: HttpErrorResponse) => {
if (err.status === 401) {
// session habis — redirect ke login
router.navigate(["/login"]);
} else if (err.status >= 500) {
console.error("Server error:", err.message);
// bisa trigger toast service di sini
}
return throwError(() => err);
})
);
};
Daftarkan bersama interceptor lain — urutan penting (auth interceptor menambah header dulu, baru error interceptor menangani response):
provideHttpClient(withInterceptors([authInterceptor, errorInterceptor]))