Sub topic 1
Why HttpClient Returns Observables
Every method on Angular's HttpClient (get, post, put, delete and the others) returns an RxJS Observable rather than a Promise. That choice affects when requests are sent, how many are sent, and how you cancel them. This chapter explains how that works so the rest of the tutorial makes sense.
Prerequisites
This chapter assumes you already know:
- TypeScript interfaces and generics
- Angular components, services and dependency injection with
inject() - Basic RxJS: what an
Observableis,subscribe(), and thepipe()method - HTTP methods, status codes and JSON
You don't need HttpClient set up yet. The next chapter covers provideHttpClient.
An Observable Is a Recipe for a Request
Calling http.get() doesn't contact the server. It returns a cold Observable, which describes a request but hasn't sent it. The request goes out only when something subscribes.
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface Todo {
id: number;
title: string;
completed: boolean;
}
@Component({
selector: 'app-observable-demo',
template: `<p>Open the Network tab in your browser's dev tools.</p>`
})
export class ObservableDemoComponent {
private readonly http = inject(HttpClient);
constructor() {
const todos$ = this.http.get<Todo[]>('/api/todos');
// No request has been sent yet.
todos$.subscribe(todos => console.log('First:', todos.length));
// Request #1 is sent.
todos$.subscribe(todos => console.log('Second:', todos.length));
// Request #2 is sent: a separate, independent HTTP call.
}
}The Network tab shows two GET /api/todos calls. Each subscription runs the recipe again.
What You Gain Over a Promise
| Behavior | Promise (`fetch`) | HttpClient Observable |
|---|---|---|
| When the request starts | Immediately on call | On `subscribe()` |
| Calling `then`/`subscribe` twice | One request, shared result | One request per subscription |
| Cancellation | Needs a separate `AbortController` | `unsubscribe()` aborts the request |
| Transforming results | Chained `then` callbacks | RxJS operators in `pipe()` |
| Multiple values | Exactly one | Can emit progress events, then the body |
By default, an HttpClient Observable emits one value (the parsed response body) and then completes. Because it completes, a plain subscription to an HTTP call won't leak memory after the response arrives. You only need to unsubscribe when you want to stop a request that is still in flight:
const subscription = this.http.get<Todo[]>('/api/todos').subscribe(console.log);
subscription.unsubscribe(); // The underlying request is aborted.This is what makes operators like switchMap useful later on. When a user types a new search term, the previous request is unsubscribed and therefore aborted.
Common Mistakes
- Forgetting to subscribe. A service method returns an Observable, a component calls it, and nothing happens. Nothing subscribed, so no request was sent. Either call
subscribe(), use theasyncpipe, or usetoSignal. - Accidental duplicate requests. Using
todos$ | asynctwice in one template subscribes twice and sends two requests. Subscribe once, or share the result. - Expecting a value synchronously. Code placed after
subscribe()runs before the response arrives. Put the logic that depends on the data inside the subscription or in operators.
Exercise
A service method loadUser() returns this.http.get<User>('/api/user'). A component calls const user$ = this.service.loadUser(); and never subscribes. Later it adds user$.subscribe() in two different places. How many HTTP requests are sent in total, and when?
Show answer
Two requests. Calling loadUser() sends nothing because the Observable is cold. Each of the two subscribe() calls starts its own independent GET /api/user request at the moment it subscribes.
Exercise
Why is it usually safe not to unsubscribe from a simple HttpClient GET call, while it is not safe to skip unsubscribing from an interval Observable?
Show answer
An HttpClient Observable emits the response and then completes, which releases the subscription automatically. An interval never completes, so its subscription stays active until you unsubscribe.