Sub topic 1
Why HttpClient Returns Observables
Prerequisites
This chapter assumes you know TypeScript interfaces and generics, and Angular components, services and dependency injection. It also assumes you can bootstrap a standalone application and have used RxJS Observables and pipe.
Why HttpClient Returns Observables
Every HttpClient method returns an Observable, not a Promise. This has three practical effects:
- Requests are lazy. No request is sent until something subscribes. If you call
http.get()and never subscribe, nothing happens on the network. - Requests can be cancelled. Unsubscribing aborts the request while it is still in flight.
- Requests can be composed. Operators such as
retry,catchErrorandswitchMapwork on the request directly.
Each subscription sends a separate request. If you subscribe twice, the API is called twice.
Setting Up HttpClient with provideHttpClient
Standalone applications register the client once in the application config:
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()]
};If you leave this out, any attempt to inject HttpClient fails with a NullInjectorError.
Putting HTTP Calls in a Data Service
Keep URLs and request logic out of components. A root-provided service injects HttpClient and returns Observables. Components then subscribe to those Observables and decide when the request runs.
Fetching Typed Data with GET
The generic parameter on get<T>() tells TypeScript the shape of the response body:
// todo.service.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 TodoService {
private readonly http = inject(HttpClient);
private readonly baseUrl = '/api/todos';
getTodos(page: number): Observable<Todo[]> {
const params = new HttpParams().set('page', page);
return this.http.get<Todo[]>(this.baseUrl, { params });
}
}Exercise
A component calls todoService.getTodos(1) but never subscribes. How many HTTP requests are sent, and why?
Show answer
None. HttpClient Observables are lazy, so the request is sent only when something subscribes.
Exercise
What error do you get when injecting HttpClient without calling provideHttpClient(), and where do you fix it?
Show answer
A NullInjectorError (No provider for HttpClient). Add provideHttpClient() to the providers array in app.config.ts.