Unsubscribe from Observables

Unsubscribe from observables in the ngOnDestroy lifecycle hook to avoid memory leaks and unintended execution of observables.
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

  selector: 'app-sample-component',
  template: '<p>Sample Component</p>'
export class SampleComponent implements OnDestroy {
  private subscription: Subscription;

  constructor() {
    // Suppose we have an observable that we subscribe to
    const observable = this.getObservable();
    this.subscription = observable.subscribe(data => {
      // handle the data from the observable

  getObservable() {
    // Example: creating the Observable (here using RxJS)
    return new Observable(subscriber => {
      // Pushing data to subscribers'data emitted');

  // Called once, just before the instance of SampleComponent is destroyed
  ngOnDestroy() {
    // Unsubscribe to ensure no memory leaks
This example shows how to use the ngOnDestroy lifecycle hook in an Angular component to unsubscribe from an observable to avoid memory leaks. It creates an instance of a subscription to an observable in the constructor, which is then unsubscribed in the ngOnDestroy method.