Reference · Frontend · Angular 16
Forms, HttpClient, dan HTTP Interceptor
Ringkasan satu halaman. Dari Lesson 0016.
Reactive vs template-driven
Reactive (ReactiveFormsModule) | Template-driven (FormsModule) | |
|---|---|---|
| Form model | eksplisit di class (FormGroup, FormControl, FormBuilder) | implisit, dibuat ngModel |
| Data model | terstruktur, immutable | tidak terstruktur, mutable ([(ngModel)]) |
| Data flow | sinkron | asinkron (tick berikutnya) |
| Validasi | fungsi (Validators.required, custom = fungsi) | directive (required, custom = directive) |
| Test | tanpa render UI | butuh change detection + fakeAsync/tick |
| Pilih kalau | form besar, dinamis, banyak validasi, perlu diuji | form kecil (signup email) |
| React | controlled input / React Hook Form | – |
form = this.fb.group({ name: ['', Validators.required], price: [0, Validators.min(0.01)] });
<form [formGroup]="form" (ngSubmit)="save()"> <input formControlName="name"> …
form.valueChanges // Observable: pipe(debounceTime, switchMap…)
setValue(obj) // struktur harus lengkap · patchValue(obj) // sebagian
HttpClient
HttpClientModulediAppModule; injectHttpClientke Angular Service.- Semua method mengembalikan Observable cold: tanpa
subscribe(atau| async) tidak ada request. get<Product[]>()= type assertion compile-time saja. Pakaiinterface.- Error:
HttpErrorResponse. Server → status 4xx/5xx; jaringan →status === 0. pipe(retry(2), catchError(...)).retry= subscribe ulang = request ulang.
HTTP Interceptor
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<unknown>, next: HttpHandler) {
const authReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
return next.handle(authReq).pipe(catchError(e => { /* 401 → login */ return throwError(() => e); }));
}
}
providers: [{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }]
| Aturan | Kenapa |
|---|---|
req.clone(...), jangan ubah req | HttpRequest readonly; retry harus melihat request yang sama |
Panggil next.handle(req) | teruskan ke interceptor berikutnya; terakhir HttpBackend |
multi: true | token berisi array interceptor; sediakan di injector yang sama dengan HttpClientModule |
| Urutan = urutan provider | request A → B, response B → A; tidak bisa diubah setelahnya |
| Kegunaan | header auth, logging/timing, cache, error global (401), XSRF |
Versi fungsi (standalone): HttpInterceptorFn + provideHttpClient(withInterceptors([...])), boleh inject().
Padanan: Axios interceptors.request/response.use (React) · Express middleware next() (backend). Glosarium: HTTP Interceptor, bukan "middleware".