Coding exercise: fetch API data and display it in a table in Angular.

Angular practical coding · Freshers

Model answer

Use HttpClient in a service or component. With the newer resource API you get value, loading and error signals; the classic way is an observable with the async pipe or toSignal. Handle loading and error states.

@Component({
  selector: 'app-users',
  template: `
    @if (loading()) { <p>Loading…</p> }
    @else if (failed()) { <p role="alert">Could not load users.</p> }
    @else {
      <table>
        <thead><tr><th>Name</th><th>Email</th><th>City</th></tr></thead>
        <tbody>
          @for (u of users(); track u.id) {
            <tr><td>{{ u.name }}</td><td>{{ u.email }}</td><td>{{ u.address.city }}</td></tr>
          }
        </tbody>
      </table>
    }`,
})
export class Users {
  private http = inject(HttpClient);
  users = signal<User[]>([]);
  loading = signal(true);
  failed = signal(false);
  constructor() {
    this.http.get<User[]>('https://jsonplaceholder.typicode.com/users').subscribe({
      next: (d) => { this.users.set(d); this.loading.set(false); },
      error: () => { this.failed.set(true); this.loading.set(false); },
    });
  }
}
interface User { id: number; name: string; email: string; address: { city: string } }

HttpClient observables complete by themselves after one response, so no unsubscribe is needed here. The public test API is only an example. Add provideHttpClient() in the app config.

Tips

Practise it yourself in the React and Angular code playground.

Learn this topic

Angular Tutorial: Beginner to Advanced .

Sign in to add your own answer.

More questions