Cancelling HTTP request when Angular Component destroyed



This content originally appeared on DEV Community and was authored by MD ASHRAF

To cancel an ongoing HTTP request when a component is destroyed, you can use the following techniques:

  1. Using takeUntil operator:
import { Component, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-example',
  template: '<p>Example Component</p>',
})
export class ExampleComponent implements OnDestroy {
  private ngUnsubscribe = new Subject<void>();

  constructor(private http: HttpClient) {
    this.http.get('https://api.example.com/data') // making http call
      .pipe(takeUntil(this.ngUnsubscribe)) // will subscribe to observanle until "ngUnsubscribe" is complete
      .subscribe((response) => {
        console.log(response);
      });
  }

  ngOnDestroy(): void {
    //marking ngUnsubscribe observable complete will unsubscribe the observable and request will get cancelled.
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}

2.Using Subscription object

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-example',
  template: '<p>Example Component</p>',
})
export class ExampleComponent implements OnDestroy {
  private subscription: Subscription;

  constructor(private http: HttpClient) {
    this.subscription = this.http.get('https://api.example.com/data')
      .subscribe((response) => {
        console.log(response);
      });
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}

However this approach is good for a single subscription if we have (n) subscriptions and we want to cancel all on component destroy(which is good practice), follow solution 1.

Why is it important?

Canceling ongoing HTTP requests when a component is destroyed is important to prevent memory leaks and improve the overall performance of your application. When a component is destroyed, any ongoing HTTP requests associated with that component should be cancelled to prevent unnecessary resource usage and potential errors.

📌📌 More Angular related topics here:
Rxjs and Angular bonding


This content originally appeared on DEV Community and was authored by MD ASHRAF