Thuta Learning
ရှာဖွေရန်
AdvancedWeb Developmentintermediate

HTTP Interceptors

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

HTTP Interceptors များသည် HTTP requests/responses များကို intercept လုပ်ပြီး modify, log, သို့မဟုတ် handle errors လုပ်နိုင်သည်။

typescript
// auth.interceptor.ts
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) {
    // Add auth token to request
    const token = localStorage.getItem('auth_token');
    
    if (token) {
      req = req.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
    }
    
    return next.handle(req);
  }
}

// logging.interceptor.ts
export class LoggingInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    console.log('Request:', req.url);
    const started = Date.now();
    
    return next.handle(req).pipe(
      tap(() => {
        const elapsed = Date.now() - started;
        console.log(`Response took ${elapsed}ms`);
      })
    );
  }
}

// app.module.ts
@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true }
  ]
})
You should see
(All HTTP requests များသည် interceptors များမှ pass ဖြစ်ပြီး token auto-add, logging စသည်ဖြင့် handle လုပ်မည်)
HTTP Interceptors | Thuta Learning