How to unsubscribe from observables in Angular

Properly unsubscribing from observables is crucial for preventing memory leaks and ensuring optimal performance in Angular applications. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented subscription cleanup patterns in countless Angular enterprise applications and admin dashboards. From my experience with Angular, the most effective approach is to use the takeUntil operator with a destroy subject pattern. This method provides automatic cleanup and prevents common memory leak issues.

Use the takeUntil operator with a destroy subject to automatically unsubscribe when the component is destroyed.

import { Component } from '@angular/core'
import { Subject } from 'rxjs'
import { takeUntil } from 'rxjs/operators'
import { UserService } from './user.service'

@Component({
  selector: 'app-users',
  template: `
    <div *ngFor="let user of users">
      {{ user.name }}
    </div>
  `
})
export class UsersComponent {
  users: any[] = []
  private destroy$ = new Subject<void>()

  constructor(private userService: UserService) {}

  ngOnInit() {
    this.userService.getUsers()
      .pipe(takeUntil(this.destroy$))
      .subscribe(users => {
        this.users = users
      })

    this.userService.getUserUpdates()
      .pipe(takeUntil(this.destroy$))
      .subscribe(update => {
        console.log('User update:', update)
      })
  }

  ngOnDestroy() {
    this.destroy$.next()
    this.destroy$.complete()
  }
}

The takeUntil operator automatically completes the observable chain when the destroy subject emits a value. Create a private destroy$ subject that emits in the ngOnDestroy lifecycle hook. All subscriptions using takeUntil(this.destroy$) will automatically unsubscribe when the component is destroyed. This pattern eliminates the need to manually track individual subscriptions and ensures complete cleanup.

This is the same subscription cleanup pattern we use in CoreUI Angular templates to prevent memory leaks and maintain optimal application performance. For HTTP requests that complete automatically, unsubscription isn’t strictly necessary, but using this pattern consistently ensures your application remains leak-free as requirements change.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Detect a Click Outside of a React Component
How to Detect a Click Outside of a React Component

CSS Selector for Parent Element
CSS Selector for Parent Element

How to Convert a Map to an Array in JavaScript
How to Convert a Map to an Array in JavaScript

How to Center a Button in CSS
How to Center a Button in CSS