Skip to main content
Angular’s HTTP client provides a simplified API for HTTP functionality in your applications. It’s built on top of the browser’s native fetch or XMLHttpRequest APIs and provides a streamlined way to communicate with backend services.

Key Features

  • Observable-based API: All HTTP methods return RxJS Observables for powerful async operations
  • Request and response interceptors: Transform requests and responses globally
  • Typed request and response objects: Full TypeScript support with generic types
  • Streamlined error handling: Structured error responses
  • Testability: Built-in testing utilities for mocking HTTP requests
  • Progress events: Track upload and download progress
  • Request cancellation: Cancel in-flight requests when needed

Getting Started

Import HttpClient

To use the HTTP client, you need to import HttpClient and configure it in your application:
import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';

@Component({
  selector: 'app-hero-list',
  template: `...`
})
export class HeroListComponent {
  private http = inject(HttpClient);
  
  getHeroes() {
    return this.http.get<Hero[]>('/api/heroes');
  }
}

Provide HTTP Client

In your application configuration, provide the HTTP client:
import { provideHttpClient } from '@angular/common/http';
import { bootstrapApplication } from '@angular/platform-browser';

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient()
  ]
});

Making Requests

The HttpClient service provides methods for all common HTTP verbs:
  • get() - Retrieve data from a server
  • post() - Send data to create a resource
  • put() - Send data to update a resource
  • patch() - Send data to partially update a resource
  • delete() - Delete a resource
  • head() - Retrieve headers only
  • options() - Retrieve supported HTTP methods
  • jsonp() - Make JSONP requests

Basic GET Request

interface Hero {
  id: number;
  name: string;
}

this.http.get<Hero[]>('/api/heroes')
  .subscribe(heroes => {
    console.log('Heroes:', heroes);
  });

POST Request with Body

const newHero = { name: 'Spider-Man' };

this.http.post<Hero>('/api/heroes', newHero)
  .subscribe(hero => {
    console.log('Created hero:', hero);
  });

Request Options

All HTTP methods accept an options object to customize the request:
this.http.get<Hero[]>('/api/heroes', {
  headers: { 'Authorization': 'Bearer token123' },
  params: { active: 'true' },
  responseType: 'json',
  observe: 'response',
  withCredentials: true
});
headers
HttpHeaders | object
HTTP headers to send with the request
params
HttpParams | object
URL query parameters
responseType
'json' | 'text' | 'blob' | 'arraybuffer'
Expected response format (defaults to ‘json’)
observe
'body' | 'response' | 'events'
What to observe in the response (defaults to ‘body’)
withCredentials
boolean
Whether to send credentials (cookies) with the request
reportProgress
boolean
Whether to report upload/download progress events

Response Types

By default, HttpClient assumes JSON responses, but you can specify other types:

JSON Response (default)

interface Config {
  apiUrl: string;
}

this.http.get<Config>('/api/config')
  .subscribe(config => {
    console.log('API URL:', config.apiUrl);
  });

Text Response

this.http.get('/api/textfile', { responseType: 'text' })
  .subscribe(text => {
    console.log('File contents:', text);
  });

Blob Response

this.http.get('/api/image.png', { responseType: 'blob' })
  .subscribe(blob => {
    const url = URL.createObjectURL(blob);
    // Use the blob URL
  });

Observing Responses

Control what part of the response you want to observe:

Body Only (default)

this.http.get<Hero[]>('/api/heroes')
  .subscribe(heroes => {
    // heroes is the response body
  });

Full Response

this.http.get<Hero[]>('/api/heroes', { observe: 'response' })
  .subscribe(response => {
    console.log('Status:', response.status);
    console.log('Headers:', response.headers);
    console.log('Body:', response.body);
  });

All Events

import { HttpEventType } from '@angular/common/http';

this.http.get('/api/data', { observe: 'events', reportProgress: true })
  .subscribe(event => {
    if (event.type === HttpEventType.DownloadProgress) {
      console.log(`Downloaded ${event.loaded} of ${event.total} bytes`);
    } else if (event.type === HttpEventType.Response) {
      console.log('Complete:', event.body);
    }
  });

Error Handling

Handle HTTP errors using RxJS operators:
import { catchError, of } from 'rxjs';

this.http.get<Hero[]>('/api/heroes')
  .pipe(
    catchError(error => {
      console.error('Error loading heroes:', error);
      return of([]); // Return empty array as fallback
    })
  )
  .subscribe(heroes => {
    console.log('Heroes:', heroes);
  });

HTTP Headers

Work with HTTP headers using the HttpHeaders class:
import { HttpHeaders } from '@angular/common/http';

const headers = new HttpHeaders()
  .set('Authorization', 'Bearer token123')
  .set('Content-Type', 'application/json');

this.http.get('/api/data', { headers })
  .subscribe(data => console.log(data));
Note: HttpHeaders is immutable, so set() returns a new instance.

URL Parameters

Add query parameters using HttpParams or a plain object:
import { HttpParams } from '@angular/common/http';

// Using HttpParams
const params = new HttpParams()
  .set('page', '1')
  .set('limit', '10');

this.http.get('/api/heroes', { params })
  .subscribe(heroes => console.log(heroes));

// Using plain object
this.http.get('/api/heroes', { 
  params: { page: '1', limit: '10' } 
})
  .subscribe(heroes => console.log(heroes));

Request Cancellation

Cancel in-flight requests by unsubscribing:
const subscription = this.http.get('/api/data')
  .subscribe(data => console.log(data));

// Cancel the request
subscription.unsubscribe();

HttpClient

Complete API reference for the HttpClient service

HttpInterceptor

Intercept and transform HTTP requests and responses

See Also