Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 74 ยท HTTP and RxJS

HttpClient: Requests and Responses

Learn Angular HttpClient: provideHttpClient and withFetch, typed GET, POST, PUT and DELETE, params and headers, HttpErrorResponse handling, with a runnable fetch-based stand-in.

Almost every real application talks to a server, and in Angular that conversation goes through HttpClient. It is a service that sends HTTP requests and gives you back observables of the responses. It parses JSON for you, lets you describe the shape of the data with TypeScript types, supports interceptors for cross-cutting concerns, and has a testing harness that fakes the network.

This lesson covers setting it up, the four main methods, query parameters and headers, typed responses (and what the types do not promise), reading the full response, and handling errors properly. Interceptors get their own lesson, HTTP Interceptors.

The typescript and html blocks are real Angular and read-only, because the site can't run the Angular compiler or reach a real API from your browser tab. The runnable examples are stand-ins: a small fetch-based client with the same shape (typed get, post, put, delete, params, headers, an error class carrying status) talking to a tiny server started inside the example itself, on loopback. It uses promises where real HttpClient uses observables, and it is not Angular's code.

Setting it up

HttpClient is not available until you provide it. In a standalone app that happens once, in app.config.ts, with provideHttpClient():

TypeScript
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { routes } from './app.routes';

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

provideHttpClient accepts features as arguments, and you will meet two now: withFetch() and withInterceptors([...]) (next lesson). By default HttpClient uses the browser's XMLHttpRequest. withFetch() makes it use the modern fetch API instead. It is the recommended choice when you render on the server (SSR and hydration), because Node has fetch built in; its main limitation is that it cannot report upload progress.

If you forget provideHttpClient, injecting HttpClient fails with a NullInjectorError: No provider for HttpClient. That is the whole fix.

A typed API service

By convention you do not call HttpClient from components. You wrap it in a service so that URLs, parameters and types live in one place:

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

export interface User {
  id: number;
  name: string;
  role: 'admin' | 'editor' | 'viewer';
}
export type NewUser = Omit<User, 'id'>;

@Injectable({ providedIn: 'root' })
export class UserApi {
  private readonly http = inject(HttpClient);
  private readonly baseUrl = '/api/users';

  list(options: { role?: string; page?: number } = {}): Observable<User[]> {
    let params = new HttpParams().set('page', options.page ?? 1);
    if (options.role) {
      params = params.set('role', options.role);   // HttpParams is immutable: keep the result
    }
    return this.http.get<User[]>(this.baseUrl, { params });
  }

  get(id: number): Observable<User> {
    return this.http.get<User>(`${this.baseUrl}/${id}`);
  }

  create(user: NewUser): Observable<User> {
    return this.http.post<User>(this.baseUrl, user);
  }

  update(user: User): Observable<User> {
    return this.http.put<User>(`${this.baseUrl}/${user.id}`, user);
  }

  remove(id: number): Observable<void> {
    return this.http.delete<void>(`${this.baseUrl}/${id}`);
  }
}

The method names mirror HTTP verbs. get and delete take (url, options?); post, put and patch take (url, body, options?). A plain object body is sent as JSON with the right Content-Type. The generic argument (get<User[]>) tells TypeScript what the body will be.

The generic is a promise to the compiler, not a check at runtime. get<User[]> does not validate anything: if the server returns something else, you get a User[]-typed value that is not one, and the error appears later, somewhere unrelated. For APIs you do not control, validate at the boundary (a schema library, or a hand-written type guard).

Query parameters and headers

Both are immutable objects: every set or append returns a new instance, and the original is untouched. Forgetting that is a classic bug (params.set('page', 2) on its own line does nothing). For simple cases you can skip the classes and pass plain objects, and Angular builds them for you:

TypeScript
this.http.get<User[]>('/api/users', {
  params: { role: 'editor', page: 2, active: true },        // numbers and booleans are fine
  headers: { 'X-Request-Source': 'user-list', Accept: 'application/json' },
});

Values are URL-encoded for you. Use HttpParams (or HttpParams with fromObject) when you need to build parameters step by step, or to send the same name several times with append.

Do not add an Authorization header to every call by hand. That belongs in an interceptor, so that it is written once.

Reading more than the body

By default you get only the parsed body. Pass observe: 'response' to receive an HttpResponse<T> with status, headers and body, and responseType when the body is not JSON:

TypeScript
this.http.get<User[]>('/api/users', { observe: 'response' }).subscribe((response) => {
  console.log(response.status);                      // 200
  console.log(response.headers.get('X-Total-Count'));
  console.log(response.body);                        // User[] | null
});

this.http.get('/reports/summary.csv', { responseType: 'text' });   // Observable<string>
this.http.get('/files/logo.png', { responseType: 'blob' });        // Observable<Blob>

Note that response.body is typed T | null. A 204 No Content response has no body, which is why delete<void> makes sense.

flowchart LR
  C["Component"] --> S["UserApi service"]
  S --> H["HttpClient<br/>returns an Observable"]
  H --> I["Interceptors<br/>(next lesson)"]
  I --> B["Backend: XHR or fetch"]
  B --> API["Server"]
  API -->|"response"| B
  B -->|"parsed body, typed"| C

Nothing is sent until the observable is subscribed to, and each subscription sends its own request.

Requests are cold

This is the point from the previous lessons that bites hardest in practice. this.http.get(...) does nothing by itself. It returns a recipe, and the request goes out when something subscribes: subscribe(), the async pipe, toSignal() or httpResource. And every subscription sends a new request:

TypeScript
const users$ = this.http.get<User[]>('/api/users');

users$.subscribe(...);   // request 1
users$.subscribe(...);   // request 2, identical

Calling post without subscribing is the typical "my save button does nothing" bug. In the other direction, using users$ | async in two places in one template sends two requests: store the result once (toSignal, or shareReplay) and read it twice. HTTP observables complete after the response, so you do not need takeUntilDestroyed to avoid leaks, although unsubscribing early (for example through switchMap) cancels the request in flight.

A runnable client

The stand-in below starts a small server on 127.0.0.1 and defines MiniHttpClient on top of fetch. It has typed get, post, put and delete, builds query strings from a params object, sends headers, parses JSON, and turns non-2xx statuses into an HttpError that carries the status and the response body. The sandbox has no internet, so the server is part of the program.

TypeScript Stand-in: a typed fetch-based client and a local API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read the output from the top: params were turned into a query string and the server filtered on them, post sent JSON and got a 201 with the new id, put replaced the record, delete returned an empty body (null in this client, null or undefined in real Angular depending on the options), and the header reached the server. Compare it with the UserApi service above: the method names and the shape of each call are the same.

Handling errors

When the server answers with a status outside 200-299, or when no answer arrives at all, the observable errors with an HttpErrorResponse. The properties you will use:

Property Meaning
status the HTTP status code, or 0 when the request never got a response (offline, DNS failure, CORS block, aborted)
statusText the status text, such as Not Found
error the response body (parsed JSON if possible), or an event/error object for status 0
message a generic description
url the request URL
flowchart TD
  R["Request fails"] --> Q{"status?"}
  Q -->|"0"| N["Network problem<br/>offline, CORS, DNS"]
  Q -->|"400-499"| C["Client error<br/>bad input, not found, unauthorized"]
  Q -->|"500-599"| S["Server error<br/>retry later, show apology"]

The status code tells you whose fault it is and what the user can do.

Translate low-level errors into messages the UI can show, close to the API service, using catchError (RxJS operators):

TypeScript
import { HttpErrorResponse } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';

get(id: number): Observable<User> {
  return this.http.get<User>(`${this.baseUrl}/${id}`).pipe(
    catchError((error: HttpErrorResponse) => {
      const message =
        error.status === 0 ? 'You appear to be offline.' :
        error.status === 404 ? `User ${id} does not exist.` :
        error.status >= 500 ? 'The server had a problem. Please try again.' :
        error.error?.message ?? 'Something went wrong.';
      return throwError(() => new Error(message));
    }),
  );
}

Two good habits. Rethrow with throwError(() => ...) (or return of(fallback) when a default is acceptable) so the caller still decides what to do. And use retry({ count: 2, delay: 500 }) only for idempotent reads: retrying a POST can create two orders.

The second stand-in shows both ideas on the same kind of client: a Lazy wrapper that sends nothing until subscribe, then three failure types (404, 500, a refused connection), a getOrDefault that works like catchError(() => of(fallback)), and a call that reads the status and headers the way observe: 'response' does.

TypeScript Stand-in: cold requests, error statuses and full responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

In the first block the key observation is the count: it stays at 0 after the request is created, then goes up by one for each subscribe. The next three lines show how the status separates problems the user must hear about differently, and why a connection that never produced a response is reported with status 0.

Where to go from here

You now have the pieces for talking to a server. Three further steps build on them:

  • HTTP Interceptors to add auth headers, logging and retries in one place.
  • Signals and RxJS interop to display responses with toSignal, and resource and httpResource to load data with a loading and error state without writing a subscription.
  • Testing, where provideHttpClientTesting() and HttpTestingController let you verify requests and fake responses without a network.

During development, a dev-server proxy (proxyConfig in angular.json, with a small proxy.conf.json) forwards /api to your backend so that the browser sees one origin and CORS rules do not get in the way.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You write this.http.post('/api/orders', order) in a method but nothing is sent. What is the most likely reason?

    HttpClient returns a cold observable. The request goes out only when something subscribes (subscribe, async pipe, toSignal, httpResource).
  2. 2. What does the generic in http.get<User[]>(url) guarantee at runtime?

    The generic is a compile-time assertion. If the server sends something different, the mismatch surfaces later, so validate data from servers you do not control.
  3. 3. params = params.set('page', 2) is needed instead of params.set('page', 2) alone because...

    HttpParams and HttpHeaders are immutable. Each modification returns a new object, and the original stays unchanged.
  4. 4. In an HttpErrorResponse, what does status 0 usually mean?

    Status 0 signals a failure before any HTTP response arrived. Authentication problems are 401 or 403.
  5. 5. Which option makes HttpClient use the fetch API instead of XMLHttpRequest?

    withFetch() is a feature passed to provideHttpClient. It is recommended with server-side rendering, and it does not support upload progress.

Summary

  • Add provideHttpClient() once in app.config.ts; withFetch() switches the backend to fetch (recommended for SSR), withInterceptors() adds interceptors.
  • Wrap HttpClient in a service; get and delete take (url, options), post, put and patch take (url, body, options).
  • The response generic is a compile-time promise, not validation; check data from untrusted servers.
  • HttpParams and HttpHeaders are immutable; plain objects work for simple cases; observe: 'response' gives status and headers; responseType handles text and blobs.
  • Requests are cold: nothing is sent until you subscribe, and each subscription sends a new request.
  • Errors arrive as HttpErrorResponse; status 0 means no response. Map them with catchError, retry only idempotent reads.
  • The snippets are read-only Angular; the fetch-based client and the local server are stand-ins.

Next: HTTP Interceptors