Mengambil Artikel dengan HttpClient Angular: Loading dan Error
Bedakan keadaan memuat, berhasil, kosong, dan gagal ketika mengambil data artikel dari API.
Daftar yang kosong belum tentu berarti tidak ada artikel. Permintaan bisa masih berjalan atau gagal. Tampilan perlu membedakan keadaan tersebut agar pengguna memahami hasilnya.
Daftarkan provideHttpClient() pada providers di konfigurasi aplikasi. Contoh komponen ini mengasumsikan GET /api/articles mengembalikan array objek dengan id dan title. Endpoint tersebut harus dibuat sendiri; bila API mengembalikan objek pagination, sesuaikan pemetaan respons.
Contoh implementasi
import { AsyncPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { catchError, map, of, startWith } from 'rxjs';
type Article = { id: number; title: string };
@Component({
selector: 'app-article-list',
standalone: true,
imports: [AsyncPipe],
template: `
@if (state$ | async; as state) {
@if (state.loading) { <p>Loading…</p> }
@else if (state.error) { <p role="alert">{{ state.error }}</p> }
@else {
@for (article of state.articles; track article.id) {
<h2>{{ article.title }}</h2>
} @empty { <p>No articles yet.</p> }
}
}
`,
})
export class ArticleList {
private http = inject(HttpClient);
state$ = this.http.get<Article[]>('/api/articles').pipe(
map(articles => ({ loading: false, articles, error: '' })),
startWith({ loading: true, articles: [] as Article[], error: '' }),
catchError(() => of({
loading: false, articles: [] as Article[], error: 'Unable to load articles.',
})),
);
}
Cara memeriksa
Gunakan network throttling untuk melihat pesan loading, respons [] untuk keadaan kosong, dan respons HTTP 500 untuk keadaan gagal. Jangan tampilkan detail exception server kepada pembaca.
Satu pemakaian AsyncPipe pada blok luar membantu menghindari beberapa subscription HTTP untuk tampilan yang sama. Tipe Article[] membantu TypeScript tetapi tidak memvalidasi JSON saat runtime. Bila API berada di domain berbeda, server API juga perlu mengatur CORS.
