
Angular Won't Unsubscribe for You: Finding the Subscriptions That Leak
- كاتب موثّق
- Angular 22
محتويات المقال
The common misconception
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
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
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.
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)); }}import { Component, inject } from '@angular/core';import { takeUntilDestroyed } from '@angular/core/rxjs-interop';@Component({ selector: 'app-ticket-page', templateUrl: './ticket-page.html' })export class TicketPage { private readonly notifications = inject(NotificationService); private readonly toast = inject(ToastService); constructor() { // Completes when this page is destroyed, so the source lets go this.notifications.messages$ .pipe(takeUntilDestroyed()) .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
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.
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.
async pipe in the template | ||
toSignal() | ||
.subscribe() to an HttpClient call | ||
.subscribe() to a service stream, interval() or fromEvent() | ||
.pipe(takeUntilDestroyed()).subscribe() | DestroyRef fires |
How to apply it in your project
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.Remove the ones you don't need Values that only feed the template become toSignal()or anasyncpipe. Then there's no subscription for you to manage.End the rest with the component Add takeUntilDestroyed()as the last operator beforesubscribe()in the constructor or a field initializer, or pass an injectedDestroyRefwhen you subscribe inngOnInitor a method.Check with a snapshot Repeat 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 asyncpipe,toSignal(), effects andDestroyRefcallbacks, 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.
التعليقات (0)