← Learning Hub
Intermediate

HttpClient: Calling an API

Angular's HttpClient talks to servers. First turn it on in app.config.ts:

Most Angular apps are front ends for a server: they load products, submit orders and save settings through HTTP requests to an API. HttpClient handles the details - JSON conversion, headers, errors - and returns Observables that fit with the rest of Angular. Keeping all API calls in services means components stay simple, and if the API address changes you fix it in one place.

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

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

Put API calls in a service

Example
// user.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface User { id: number; name: string; email: string; }

@Injectable({ providedIn: 'root' })
export class UserService {
  private http = inject(HttpClient);
  private base = 'https://jsonplaceholder.typicode.com';

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(`${this.base}/users`);
  }
  addUser(user: Omit<User, 'id'>): Observable<User> {
    return this.http.post<User>(`${this.base}/users`, user);
  }
}

Show the data in a component

toSignal() turns the HTTP result into a signal, so the template can read it like any other signal.

Example
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { UserService } from './user.service';

@Component({
  selector: 'app-users',
  template: `
    @if (users(); as list) {
      <ul>
        @for (u of list; track u.id) { <li>{{ u.name }} - {{ u.email }}</li> }
      </ul>
    } @else {
      <p>Loading...</p>
    }
  `,
})
export class Users {
  private userService = inject(UserService);
  users = toSignal(this.userService.getUsers());   // undefined until the answer arrives
}

Handling errors

Example
import { catchError, of } from 'rxjs';

users = toSignal(
  this.userService.getUsers().pipe(
    catchError(() => {
      this.error.set('Could not load users');
      return of([]);
    })
  )
);
Newer Angular versions also have httpResource(), which gives you value(), isLoading() and error() signals in one go. Learn HttpClient first - httpResource is built on it.
Key points
  • Turn on HttpClient with provideHttpClient().
  • Put API calls in services.
  • toSignal() shows HTTP results in templates.
  • Handle errors and show friendly messages.

📝 Test yourself

1. Where do you switch on HttpClient?
2. What does toSignal() do with an Observable?
3. Fill in the HttpClient method for reading data:
this.http.<User[]>('/api/users')