HttpClient

Type-Safe HTTP With RxJS

HttpClient

HttpClient is Angular's wrapper around fetch — returning typed Observables for GET, POST, PUT, PATCH, and DELETE.

4 min read Level 2/5 #angular#http
What you'll learn
  • Provide HttpClient with provideHttpClient
  • Type the response with a generic parameter
  • Send a POST with a request body

HttpClient returns Observables instead of Promises. That sounds heavier than fetch but it pays off: cancellation, retries, and operator composition come for free.

Provide it

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

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

GET with a typed response

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

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

@Injectable({ providedIn: 'root' })
export class UsersService {
  private http = inject(HttpClient);

  list() {
    return this.http.get<User[]>('/api/users');
  }
}

The <User[]> generic does not validate the response at runtime — it just tells TypeScript what to expect. Pair with a parser like Zod for runtime safety.

POST, PUT, DELETE

create(input: { name: string }) {
  return this.http.post<User>('/api/users', input);
}

remove(id: string) {
  return this.http.delete<void>(`/api/users/${id}`);
}

Cancellation

Because HttpClient returns an Observable, unsubscribing aborts the underlying request. Combined with switchMap, you get free debounced search:

query.valueChanges.pipe(
  debounceTime(200),
  switchMap(q => this.http.get<User[]>(`/api/search?q=${q}`)),
);

A new keystroke cancels the in-flight request — no race conditions.

HTTP Interceptors →