TExcelTAD
Home › Angular › HttpClient

HttpClient

Most apps load and save data through a web API. Angular's HttpClient sends HTTP requests, parses JSON, supports typed responses and lets you plug in interceptors for cross-cutting concerns like authentication headers or error logging.

Setup

Register the HTTP client once in app.config.ts:

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

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

withFetch() uses the browser's fetch API under the hood (recommended, and required for good server-side rendering support).

A data service

Keep HTTP calls in a service, not in components. Methods return Observables typed with your interface:

ts
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface Todo { id: number; title: string; completed: boolean; }

@Injectable({ providedIn: 'root' })
export class TodoApi {
  private http = inject(HttpClient);
  private base = 'https://api.example.com/todos';

  list(limit = 5): Observable<Todo[]> {
    const params = new HttpParams().set('_limit', limit);
    return this.http.get<Todo[]>(this.base, { params });
  }

  create(title: string): Observable<Todo> {
    return this.http.post<Todo>(this.base, { title, completed: false });
  }

  toggle(todo: Todo): Observable<Todo> {
    return this.http.patch<Todo>(`${this.base}/${todo.id}`, { completed: !todo.completed });
  }

  remove(id: number): Observable<void> {
    return this.http.delete<void>(`${this.base}/${id}`);
  }
}
Method HTTP verb Typical use
get<T>(url, opts) GET Read data
post<T>(url, body) POST Create
put<T>(url, body) / patch<T>(url, body) PUT / PATCH Replace / partially update
delete<T>(url) DELETE Remove

Note: HttpClient Observables are cold: nothing is sent until something subscribes. Calling api.list() without subscribing does nothing.

Showing the data in a component

toSignal() subscribes to the Observable and exposes the latest value as a signal — no manual subscribe/unsubscribe:

angular · try it yourself
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { TodoApi } from './todo-api';

@Component({
  selector: 'app-todo-list',
  template: `
    @if (todos(); as list) {
      <ul>
        @for (t of list; track t.id) {
          <li [class.done]="t.completed">{{ t.title }}</li>
        }
      </ul>
    } @else {
      <p>Loading…</p>
    }
  `,
  styles: `.done { text-decoration: line-through; color: #888; }`,
})
export class TodoList {
  private api = inject(TodoApi);
  todos = toSignal(this.api.list(3));   // undefined until the response arrives
}

Tip: Newer Angular versions also offer httpResource(), which wraps a GET request in a signal-based resource with value(), isLoading() and error(). It is great for reactive loading driven by other signals.

Handling errors

Requests can fail. Use RxJS's catchError to turn an error into a fallback value, or let it propagate to the UI:

ts
this.http.get<Todo[]>(url).pipe(
  retry(2),
  catchError((err: HttpErrorResponse) => {
    console.error('Request failed with status', err.status);
    return of([]);   // show an empty list instead
  }),
);

The pattern — try, retry a few times, then fall back — is easy to model with Promises in plain TypeScript:

ts · try it yourself
export {}; // makes this file a module, so top-level await is allowed

interface Todo { id: number; title: string; }

let attempts = 0;
async function fakeGet(): Promise<Todo[]> {
  attempts++;
  if (attempts < 3) throw new Error(`503 Service Unavailable (attempt ${attempts})`);
  return [{ id: 1, title: 'Write the API service' }];
}

async function withRetry<T>(fn: () => Promise<T>, retries: number, fallback: T): Promise<T> {
  for (let i = 0; i <= retries; i++) {
    try {
      return await fn();
    } catch (err) {
      console.log('failed:', (err as Error).message);
    }
  }
  return fallback;
}

const alwaysDown = async (): Promise<Todo[]> => { throw new Error('offline'); };

console.log(await withRetry(fakeGet, 2, []));
console.log(await withRetry(alwaysDown, 1, []));
failed: 503 Service Unavailable (attempt 1)
failed: 503 Service Unavailable (attempt 2)
[ { id: 1, title: 'Write the API service' } ]
failed: offline
failed: offline
[]

Interceptors

An interceptor sees every request and response. It's the right place to add an auth token, log timings or handle 401 errors globally:

ts
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { Auth } from './auth';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(Auth).token();
  if (!token) return next(req);
  return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};

Requests are immutable, so you clone() them with changes. Interceptors form a chain — each calls next to pass the request on:

ts · try it yourself
interface Req { url: string; headers: Record<string, string>; }
type Next = (req: Req) => string;
type Interceptor = (req: Req, next: Next) => string;

const auth: Interceptor = (req, next) =>
  next({ ...req, headers: { ...req.headers, Authorization: 'Bearer abc123' } });

const logging: Interceptor = (req, next) => {
  console.log('→', req.url);
  const res = next(req);
  console.log('←', res);
  return res;
};

const backend: Next = (req) => `200 OK (headers: ${Object.keys(req.headers).join(', ')})`;

function chain(interceptors: Interceptor[], final: Next): Next {
  return interceptors.reduceRight<Next>((next, ic) => (req) => ic(req, next), final);
}

const send = chain([logging, auth], backend);
send({ url: '/api/todos', headers: { Accept: 'application/json' } });
→ /api/todos
← 200 OK (headers: Accept, Authorization)

Test yourself

Where do you enable HttpClient in a standalone app?

  1. Import HttpClientModule in every component
  2. provideHttpClient() in app.config.ts
  3. Add it to index.html
  4. It is always enabled

When does http.get(url) actually send the request?

  1. Immediately when called
  2. When the Observable is subscribed (e.g. by toSignal or the async pipe)
  3. On the next page load
  4. After 1 second

Why does an interceptor call req.clone({...}) instead of modifying req?

  1. Requests are immutable
  2. clone is faster
  3. To send the request twice
  4. It is required by TypeScript