Asosiy matnga o'tish
ITIT Interview
Angular

HttpClient va interceptor'lar

HttpClient bilan so'rovlar, tiplangan javoblar, xatolarni boshqarish va qayta urinish, funksional interceptor'lar, autentifikatsiya tokeni, yuklanish holati va keshlash.

O'rganildi: 0 / 4
Progress

Sozlash

app.config.ts
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withFetch(), withInterceptors([authInterceptor, errorInterceptor])),
  ],
};

So'rovlar

product.service.ts
import { HttpClient, HttpParams } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class ProductService {
  private http = inject(HttpClient);
  private baseUrl = '/api/products';

  list(page = 1, search = '') {
    const params = new HttpParams().set('page', page).set('q', search);
    return this.http.get<Product[]>(this.baseUrl, { params });
  }

  get(id: number) {
    return this.http.get<Product>(`${this.baseUrl}/${id}`);
  }

  create(data: NewProduct) {
    return this.http.post<Product>(this.baseUrl, data);
  }

  update(id: number, data: Partial<Product>) {
    return this.http.patch<Product>(`${this.baseUrl}/${id}`, data);
  }

  remove(id: number) {
    return this.http.delete<void>(`${this.baseUrl}/${id}`);
  }
}

HttpClient metodlari cold Observable qaytaradi: obuna bo'lmaguncha so'rov yuborilmaydi, har bir obuna esa yangi so'rov yuboradi.

this.productService.create(data);              // hech narsa bo'lmaydi
this.productService.create(data).subscribe();  // so'rov ketadi

Generik tur (get<Product>) faqat TypeScript uchun: server boshqa narsa qaytarsa, Angular buni tekshirmaydi. Muhim joylarda javobni zod kabi kutubxona bilan tekshirish mumkin.

Komponentda ishlatish

export class ProductListComponent {
  private api = inject(ProductService);

  // 1. Signal'ga aylantirish
  products = toSignal(this.api.list(), { initialValue: [] });

  // 2. Yoki httpResource (yangi API): parametrlar o'zgarsa qayta yuklanadi
  page = signal(1);
  productsRes = httpResource<Product[]>(() => `/api/products?page=${this.page()}`);
}
@if (productsRes.isLoading()) { <app-spinner /> }
@for (p of productsRes.value() ?? []; track p.id) { <app-product-card [product]="p" /> }

Xatolar va qayta urinish

import { catchError, retry, throwError, timer } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

this.http.get<User>('/api/me').pipe(
  retry({ count: 2, delay: (_err, attempt) => timer(attempt * 1000) }),   // 1s, 2s kutib qayta urinish
  catchError((err: HttpErrorResponse) => {
    if (err.status === 404) return of(null);
    return throwError(() => new Error("Ma'lumotni yuklab bo'lmadi"));
  }),
);

POST kabi idempotent bo'lmagan so'rovlarni ko'r-ko'rona qayta urinmang: buyurtma ikki marta yaratilishi mumkin.

Interceptor'lar

Har bir so'rov va javobni markazlashgan holda qayta ishlash: token qo'shish, xatolarni ushlash, log, yuklanish indikatori.

auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token();
  if (!token || !req.url.startsWith('/api')) return next(req);

  const authReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });   // so'rov o'zgarmas, clone kerak
  return next(authReq);
};
error.interceptor.ts
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  const router = inject(Router);
  const toast = inject(ToastService);

  return next(req).pipe(
    catchError((err: HttpErrorResponse) => {
      if (err.status === 401) router.navigate(['/login']);
      else if (err.status >= 500) toast.error('Server xatosi, keyinroq urinib ko\'ring');
      return throwError(() => err);
    }),
  );
};

Interceptor'lar withInterceptors([...]) dagi tartibda so'rovga, teskari tartibda javobga qo'llanadi.

Tokenni yangilash

401 kelganda refresh token bilan yangi access token olib, so'rovni qayta yuborish mumkin. Bir vaqtda kelgan bir nechta 401 uchun faqat bitta refresh so'rovi yuborilishi kerak: qolganlari uning natijasini kutadi (shareReplay yoki umumiy Subject bilan).

Intervyu savollari

Ushbu sahifada