Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

Unsubscribing with takeUntilDestroyed in Angular

Use Angular’s takeUntilDestroyed to clean up Observable subscriptions with the correct DestroyRef and lifecycle scope.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Angular’s takeUntilDestroyed in an Observable pipeline to end its subscription when the relevant Angular lifecycle scope is destroyed. Import it from @angular/core/rxjs-interop; omit the argument in an injection context, or pass the correct DestroyRef when calling it outside one.

What takeUntilDestroyed does

takeUntilDestroyed is an RxJS operator that completes the Observable when its calling context is destroyed. Angular marks the API stable since v19.0. It can clean up subscriptions to long-lived streams and prevent later callbacks from interacting with a component or directive that no longer exists. See Angular’s API reference.

As an Amazon Associate I earn from qualifying purchases.

Place it in the pipeline before subscribe. When destruction occurs, the operator completes the resulting Observable, which ends the subscription.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use it in an injection context

During setup code that runs in an Angular injection context, such as a constructor, the operator can obtain the current DestroyRef automatically:

import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

this.notifications
  .pipe(takeUntilDestroyed())
  .subscribe((message) => this.show(message));

Angular’s RxJS interop guide documents this optional-argument pattern.

Pass DestroyRef outside an injection context

A method called later—for example, from a user action—may run outside an injection context. In that case, inject DestroyRef while the class is being created, then pass it to the operator when setting up the subscription:

import {DestroyRef, inject} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

private readonly destroyRef = inject(DestroyRef);

startListening() {
  this.notifications
    .pipe(takeUntilDestroyed(this.destroyRef))
    .subscribe((message) => this.show(message));
}

The important distinction is when the operator is called: if the call is outside an injection context, supply the reference explicitly.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the DestroyRef scope deliberately

A DestroyRef follows the scope from which it is obtained. In a component or directive, it follows that instance; in other code, it follows the corresponding injector. Angular describes this behavior in its DestroyRef API reference.

This matters especially in services. A service’s lifetime depends on its injector scope, so a subscription tied to a service’s DestroyRef does not necessarily end when one component using that service is destroyed. If cleanup must follow a particular component, make sure the reference belongs to that component’s scope rather than assuming the service reference has the same lifetime.

What counts as destruction?

Angular may destroy a component when it is no longer shown, including when an @if block hides it, or after navigation removes it from the view. Cleanup is tied to this lifecycle event, not only to a full page reload. See Angular’s component lifecycle guide.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When this cleanup is useful—and when another approach fits

Long-lived streams and imperative subscriptions

Use takeUntilDestroyed when TypeScript code subscribes to a stream that may remain active for the lifetime of a component, directive, or other intended scope. It makes the owner of that subscription’s cleanup explicit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

HttpClient requests

Angular documents that unsubscribing aborts an in-progress HttpClient request. However, these Observables usually complete when a response arrives, so lifecycle cleanup is most significant when a request may still be running at destruction or when you need to prevent callbacks from reaching a destroyed view. Angular’s HTTP guide also points to AsyncPipe and toSignal as ways to dispose of subscriptions.

Template-bound values

If the template consumes the stream, AsyncPipe may be a more direct fit. If the value should be exposed as a signal, consider toSignal. For imperative TypeScript subscriptions, takeUntilDestroyed provides lifecycle-based cleanup. The right choice depends on where the subscription is created and which lifecycle scope should own it.

Router event example

Angular also demonstrates using the operator with Router.events. In a service method that starts tracking, retain an injected DestroyRef and pass it explicitly if the method runs outside an injection context. See the routing lifecycle and events guide.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.