الانتقال إلى المحتوى
FrontendAngular· 7 دقائق للقراءة

Angular Won't Unsubscribe for You: Finding the Subscriptions That Leak

Angular cleans up what it created. A subscribe() you wrote lives as long as its source, not your component.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Angular 22
محتويات المقال

A support agent opens a ticket, goes back to the list, and opens another one. By the fifth ticket, every incoming message pops up five identical toasts, and the tab's memory keeps climbing through the shift. The ticket page subscribes to a notification stream in its constructor to show those toasts. Each visit created a page and a subscription; each exit destroyed the page, and none of the subscriptions.

The common misconception

The belief: when Angular destroys a component, it tears down everything that component started, including every subscription it opened. Unsubscribing by hand is a leftover from older Angular versions.

There's real evidence for it. The async pipe unsubscribes when its component is destroyed. toSignal() does the same, and so do effects. Most HttpClient subscriptions end by themselves because the Observable completes after the response, so code that subscribes to HTTP calls and never unsubscribes rarely shows a problem. After a few years of that, it's easy to conclude that cleanup is the framework's job. It is, but only for the subscriptions the framework made.

What actually happens

Angular cleans up only what it knows about

Destroying a component removes its DOM, runs ngOnDestroy and every callback registered with its DestroyRef. That covers a lot: the async pipe unsubscribes in its own ngOnDestroy, and toSignal() and effect() register their cleanup with the DestroyRef of the place they were created. A plain .subscribe() registers nothing. It returns a Subscription object, which the RxJS guide describes as a disposable resource with one important method, unsubscribe(). If your code drops that object, nobody is left to call the method.

The source holds your component

A subscription is a reference from the source to your callback, and your callback refers to the component through this. As long as the source is alive, so is that chain. A source in a root service, an interval(), a fromEvent(window, ...) or a WebSocket lives as long as the app, so it keeps every subscribed callback and every component those callbacks touch. Garbage collection can't free a destroyed component that's still reachable, and the callback still runs on every new value. That's the and the five toasts, from one line.

TypeScript ticket-page.ts
import { Component, inject } from '@angular/core';@Component({ selector: 'app-ticket-page', templateUrl: './ticket-page.html' })export class TicketPage {  private readonly notifications = inject(NotificationService);  private readonly toast = inject(ToastService);  constructor() {    // Lives as long as the root service, not as long as this page    this.notifications.messages$.subscribe((m) => this.toast.show(m.text));  }}

takeUntilDestroyed() completes the Observable when the component's DestroyRef fires, which unsubscribes from the source and releases the callback. Called in the constructor or a field initializer, it finds the DestroyRef by itself. Called later, in ngOnInit or a method, it needs one passed in, because it depends on the to find it.

The safest subscription is the one you don't write

The toasts need a subscribe(), because showing a toast is a side effect. Many component subscriptions aren't like that: they copy each value into a field so the template can display it. Those can skip the manual subscription entirely and let Angular own it.

TypeScript inbox-badge.ts
import { Component, inject } from '@angular/core';import { toSignal } from '@angular/core/rxjs-interop';@Component({  selector: 'app-inbox-badge',  template: `<span class="badge">{{ unread() }}</span>`,})export class InboxBadge {  private readonly notifications = inject(NotificationService);  // No subscribe() to forget: toSignal() unsubscribes on destroy  readonly unread = toSignal(this.notifications.unread$, { initialValue: 0 });}

toSignal() subscribes once, keeps the latest value in a signal, and registers its own cleanup with the component's DestroyRef. The initialValue covers the moment before the stream's first value, so the template never sees undefined.

HTTP subscriptions end, but not always in time

HttpClient Observables usually complete once the response arrives, which is why the Angular HTTP guide says there's usually no risk of a memory leak if you don't clean them up. The same guide still strongly recommends cleaning them up when the component is destroyed, for a different reason: a slow response can arrive after the user has left, and the callback then runs against a destroyed component, writing state nobody displays or navigating from a page that's gone. Unsubscribing also aborts a request that's still in flight.

SubscriptionCleaned up for you?Why
async pipe in the templateYesThe pipe unsubscribes when its view is destroyed
toSignal()YesIt unsubscribes when its injection context is destroyed
.subscribe() to an HttpClient callUsually ends itselfIt completes after the response, which may be after destroy
.subscribe() to a service stream, interval() or fromEvent()NoThe source outlives the component
.pipe(takeUntilDestroyed()).subscribe()YesIt completes when the DestroyRef fires

How to apply it in your project

  1. List every manual subscribe()Search components, directives and services for .subscribe(. For each one, find out how long its source lives and whether it completes on its own.
  2. Remove the ones you don't needValues that only feed the template become toSignal() or an async pipe. Then there's no subscription for you to manage.
  3. End the rest with the componentAdd takeUntilDestroyed() as the last operator before subscribe() in the constructor or a field initializer, or pass an injected DestroyRef when you subscribe in ngOnInit or a method.
  4. Check with a snapshotRepeat the heap snapshot after the fix: navigate in and out, and confirm the component count drops back to zero.

Key takeaways

  • Angular cleans up the async pipe, toSignal(), effects and DestroyRef callbacks, not subscriptions you open.
  • A long-lived source keeps your callback, and the destroyed component behind it, alive and running.
  • takeUntilDestroyed() ties a subscription to the component, but in a root service it lasts as long as the app.
  • Even HTTP subscriptions deserve cleanup: a late response can still run its callback after the component is gone.

📚 المصادر

  1. Unsubscribing with takeUntilDestroyed — Angular
  2. Making HTTP requests — Angular
  3. Subscription — RxJS
  4. toSignal — Angular API
  5. Record heap snapshots — Chrome DevTools

التعليقات (0)