DEV Community

Cover image for Cancelling HTTP request when Angular Component destroyed
MD ASHRAF
MD ASHRAF

Posted on

Cancelling HTTP request when Angular Component destroyed

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();
  }
}
Enter fullscreen mode Exit fullscreen mode

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();
  }
}

Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
mhdmatheen profile image
Matheen

This information is very much needed for me. Thank you for sharing.

Collapse
 
md_ashraf_dev_to profile image
MD ASHRAF

Thank you so much for your comment and I am happy that it helped you. Please let me know if you want more topics. I'll try my best to post the same.