Angular Unsusbcribe

This is a naive but reliable way to unsubscribe from subscriptions in Angular. It should always work, but it isn't always necessary.

  • import { Subscription } from 'rxjs';
  • add implements OnDestroy to your class and add the necessary import
  • add a property to your class private subscriptions: Subscription[] = [];
  • when subscribing, push the result of that subscription to the subscriptions array this.subscriptions.push(
  • add or update your ngOnDestroy ngOnDestroy(): void { this.subscriptions.forEach(x => x.unsubscribe()); }