
http.get() Sends Nothing Until You Subscribe (and Every Subscribe Sends Again)
- كاتب موثّق
- Angular 22
محتويات المقال
GET /api/me is called three times on every page view. And users say the Save button does nothing: no error, no message, and the Network panel shows no PUT at all. Both bugs come from the same assumption about what one line, this.http.get(), actually does.
The common misconception
http.get() sends the request, like fetch() does. The it returns is a handle to that response, so subscribing to it twice simply reads the same answer twice.
fetch() starts the request the moment you call it, and a Promise holds one result that every .then() shares. An Observable looks like a Promise that can emit more than once, so it's natural to assume the same model. And in the simplest case, one subscribe() right after the call, both models predict the same thing: one request, one response. The differences only show up when there are zero subscribers or more than one.
What actually happens
The Observable is a blueprint; subscribe() runs it
HttpClient returns what RxJS calls a . Building it does no network work at all. Angular's HTTP guide describes these Observables as blueprints for requests: the request is dispatched only when something subscribes, and each subscription is independent. The RxJS guide puts it another way: subscribing to an Observable is like calling a function. Two calls run the function twice; two subscriptions run the request twice.
map(), catchError() or retry() onto the Observable before anything is sent, and they apply to every request it makes. It's why the guide's recommended service simply returns this.http.get<User>(...) from a method: the service describes the request, and the caller decides when, and how often, it runs.
this.http.put(...) and threw away the Observable it got back, so no request was ever made, and no error appeared because nothing had failed. The HTTP guide has an explicit reminder for exactly this: subscribe to mutation Observables, or they won't fire.
import { HttpClient } from '@angular/common/http';import { Component, inject, signal } from '@angular/core';@Component({ selector: 'app-profile-form', templateUrl: './profile-form.html' })export class ProfileForm { private readonly http = inject(HttpClient); readonly draft = signal({ name: '', email: '' }); readonly saved = signal(false); save() { // Without subscribe(), put() would only build the request this.http .put('/api/me', this.draft()) .subscribe(() => this.saved.set(true)); }}Every subscriber gets its own request
GETs come from the template. Each async pipe is its own subscriber, so a template that reads user$ three times runs the blueprint three times. The same applies to anything else that subscribes: a toSignal() call, a second subscribe() in a service, and the retry() operator, which recovers from an error by subscribing again and therefore sending a fresh request. Nothing in that template looks expensive, because the cost hides behind a pipe, which is why duplicate requests usually show up in the backend's logs before anyone spots them in the code.
import { AsyncPipe } from '@angular/common';import { HttpClient } from '@angular/common/http';import { Component, inject } from '@angular/core';@Component({ selector: 'app-profile', imports: [AsyncPipe], template: ` <h1>{{ (user$ | async)?.name }}</h1> <img [src]="(user$ | async)?.avatarUrl" alt="" /> <p>{{ (user$ | async)?.email }}</p> `,})export class Profile { private readonly http = inject(HttpClient); // A blueprint: each async pipe subscribes and sends its own GET readonly user$ = this.http.get<User>('/api/me');}import { HttpClient } from '@angular/common/http';import { Component, inject } from '@angular/core';import { toSignal } from '@angular/core/rxjs-interop';@Component({ selector: 'app-profile', template: ` @if (user(); as u) { <h1>{{ u.name }}</h1> <img [src]="u.avatarUrl" alt="" /> <p>{{ u.email }}</p> } `,})export class Profile { private readonly http = inject(HttpClient); // One subscription, one GET; the template reads the signal readonly user = toSignal(this.http.get<User>('/api/me'));}toSignal() subscribes once, immediately, and stores the latest value in a signal that the template can read as often as it likes. Reading a signal doesn't subscribe to anything. The subscription is cleaned up when the component is destroyed.
Unsubscribing cancels; completing ends it
HttpClient Observable while the request is in flight aborts the request, which is why an async pipe cancels a slow request when the user leaves the page, and why switchMap drops stale searches. And once the response arrives, the Observable usually completes, so a finished request doesn't keep a subscription alive.
httpResource() turns this around on purpose. It's built on HttpClient but starts its request eagerly, sends a new one when a signal it reads changes, and cancels the one still pending. The guide recommends it for reading data, not for mutations like PUT.
http.get() sends the request | subscribe() sends it |
put() still saves | |
retry() replays the last response |
How to apply it in your project
Count requests in the Network panel Open each main page with the Network panel filtered to Fetch/XHR. Every duplicated request points to an Observable with more than one subscriber. Find unsubscribed mutations Search for .post(,.put(,.patch(and.delete(and check that each result is subscribed to, returned to a caller that subscribes, or passed to an operator that does.Subscribe once per value Convert template reads to toSignal()or a single@if (... | async; as x), and give services one method per request instead of shared Observables that many callers subscribe to.Share on purpose When several parts of the app need the same response, share it explicitly with a signal or shareReplay(), and decide when the cached value must be refreshed.
Key takeaways
HttpClientmethods return cold Observables: blueprints that send nothing until something subscribes.Each subscription sends its own request, including each asyncpipe,toSignal()and everyretry().A mutation you don't subscribe to never reaches the server, and no error tells you so. Subscribe once and read the result many times, with toSignal(), a singleasyncpipe or an explicit share.
التعليقات (0)