Angular 19 httpResource API Rehberi: Modern HTTP İstekleri (2026)

06.01.2026 20:01 Haber

Angular 19.2 ile gelen httpResource API, HTTP isteklerini yönetme şeklimizi tamamen değiştiriyor! Race condition'lar, loading state yönetimi, error handling... Tüm bu karmaşık işlemler artık çok daha basit. Alesta Web olarak bu rehberde Angular'ın yeni resource API'sini detaylı olarak inceleyeceğiz ve gerçek dünya örnekleriyle öğreneceğiz.

httpResource Nedir? (What is httpResource?)

Angular 19.2'de tanıtılan httpResource, HTTP endpoint'lerinden veri çekmeyi kolaylaştıran yeni bir API. Geleneksel HttpClient'a göre önemli avantajlar sunuyor:

  • Otomatik race condition önleme - Birden fazla istek çakışmaz
  • Built-in loading state - Yükleniyor durumu otomatik takip edilir
  • Error handling - Hata yönetimi entegre
  • Signal-based - Angular Signals ile tam uyum
  • Reactive - Parametre değiştiğinde otomatik yeniden fetch
? Bilgi / Info:

httpResource, Angular 19.2'de experimental olarak eklendi. Alesta Web olarak production'da kullanmadan önce test etmenizi öneriyoruz.

Temel Kullanım (Basic Usage)

Eski Yöntem (HttpClient):

// Geleneksel yaklaşım
@Component({...})
export class UserComponent implements OnInit {
  users: User[] = [];
  loading = false;
  error: string | null = null;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.loading = true;
    this.http.get<User[]>('/api/users').subscribe({
      next: (data) => {
        this.users = data;
        this.loading = false;
      },
      error: (err) => {
        this.error = err.message;
        this.loading = false;
      }
    });
  }
}

Yeni Yöntem (httpResource):

import { httpResource } from '@angular/common/http';

@Component({...})
export class UserComponent {
  // Tek satırda tüm işlem!
  usersResource = httpResource<User[]>({
    url: '/api/users'
  });

  // Template'de kullanım:
  // {{ usersResource.value() }}     - Data
  // {{ usersResource.isLoading() }} - Loading state
  // {{ usersResource.error() }}     - Error
}

Gördüğünüz gibi, Alesta Web olarak söyleyebiliriz ki kod miktarı yarıdan fazla azaldı!

Loading ve Error States

httpResource, state yönetimini otomatik olarak halleder:

// Component
@Component({
  template: `
    @if (productsResource.isLoading()) {
      <div class="spinner">Yükleniyor...</div>
    }

    @if (productsResource.error(); as error) {
      <div class="error">Hata: {{ error.message }}</div>
    }

    @if (productsResource.value(); as products) {
      <ul>
        @for (product of products; track product.id) {
          <li>{{ product.name }} - {{ product.price | currency }}</li>
        }
      </ul>
    }
  `
})
export class ProductListComponent {
  productsResource = httpResource<Product[]>({
    url: '/api/products',
    // Opsiyonel: Transform response
    transform: (response) => response.data
  });

  // Manuel refresh
  refresh() {
    this.productsResource.reload();
  }
}
✅ Alesta Web İpucu:

httpResource Signal-based olduğu için, Angular'ın change detection'ı ile mükemmel çalışır. Zone.js overhead'i minimum!

rxResource ile Streaming (Streaming with rxResource)

RxJS Observable'ları ile çalışmak istiyorsanız, rxResource kullanabilirsiniz:

import { rxResource } from '@angular/core/rxjs-interop';
import { interval, switchMap } from 'rxjs';

@Component({...})
export class LiveDataComponent {
  // Her 5 saniyede bir güncelleme
  liveResource = rxResource({
    loader: () => interval(5000).pipe(
      switchMap(() => this.http.get<StockPrice[]>('/api/stocks'))
    )
  });

  constructor(private http: HttpClient) {}
}

// Veya WebSocket ile real-time data
@Component({...})
export class ChatComponent {
  messagesResource = rxResource({
    loader: () => this.websocketService.messages$
  });
}

Reactive Parameters:

@Component({...})
export class SearchComponent {
  searchTerm = signal('');

  // searchTerm değiştiğinde otomatik fetch
  searchResults = httpResource<SearchResult[]>({
    url: () => `/api/search?q=${this.searchTerm()}`,
    // Debounce için
    debounce: 300
  });

  onSearch(term: string) {
    this.searchTerm.set(term);
    // Otomatik olarak yeni istek atılır!
  }
}

Gerçek Dünya Örneği: E-Ticaret Ürün Sayfası

Alesta Web projelerinde kullandığımız pattern:

// product-detail.component.ts
import { httpResource } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';

@Component({
  template: `
    <div class="product-page">
      @if (productResource.isLoading()) {
        <app-skeleton-loader />
      }

      @if (productResource.error()) {
        <app-error-message
          [message]="productResource.error()?.message"
          (retry)="productResource.reload()" />
      }

      @if (productResource.value(); as product) {
        <div class="product-detail">
          <img [src]="product.image" [alt]="product.name">
          <h1>{{ product.name }}</h1>
          <p class="price">{{ product.price | currency:'TRY' }}</p>
          <p>{{ product.description }}</p>

          <button (click)="addToCart(product)">
            Sepete Ekle
          </button>
        </div>

        <!-- İlgili ürünler -->
        @if (relatedResource.value(); as related) {
          <app-related-products [products]="related" />
        }
      }
    </div>
  `
})
export class ProductDetailComponent {
  private route = inject(ActivatedRoute);
  private cartService = inject(CartService);

  // URL'den product ID al
  productId = toSignal(
    this.route.paramMap.pipe(map(p => p.get('id')))
  );

  // Ürün detayı
  productResource = httpResource<Product>({
    url: () => `/api/products/${this.productId()}`
  });

  // İlgili ürünler
  relatedResource = httpResource<Product[]>({
    url: () => `/api/products/${this.productId()}/related`,
    // Ana ürün yüklendikten sonra
    enabled: () => !!this.productResource.value()
  });

  addToCart(product: Product) {
    this.cartService.add(product);
  }
}
⚠️ Dikkat / Warning:

httpResource experimental API olduğu için, major version güncellemelerinde breaking change olabilir. Alesta Web olarak wrapper service kullanmanızı öneriyoruz.

Best Practices

Yapın ✅ Yapmayın ❌
Resource'ları component seviyesinde tanımlayın Her yerde yeni resource oluşturmayın
Error boundary kullanın Hataları görmezden gelmeyin
Loading state için skeleton kullanın Boş ekran göstermeyin
Retry mekanizması ekleyin Network hatalarını ignore etmeyin

Gereksinimler:

  • Angular 19.2 veya üzeri
  • TypeScript 5.6+
  • Zone.js (optional ama önerilen)

? Kaynaklar ve Referanslar / Sources and References

✅ Sonuç: Angular'da HTTP Yeni Çağ! (New Era of HTTP in Angular!)

httpResource API, Angular'da veri fetching'i çok daha kolay hale getiriyor. Alesta Web olarak yeni projelerimizde bu API'yi aktif olarak kullanıyoruz.

Bu rehberde öğrendikleriniz / What you learned:

  • ✅ httpResource API temel kullanımı
  • ✅ Loading, error ve success state yönetimi
  • ✅ rxResource ile streaming data
  • ✅ Reactive parameters ile auto-fetch
  • ✅ E-ticaret örneği ile gerçek dünya uygulaması

Faydalı Linkler / Useful Links:

© 2026 AlestaWeb - Tüm hakları saklıdır. Angular 19 httpResource rehberi.

WM Tools
💫

WebMaster Tools

15 Profesyonel Araç