In Angular 8, you can cancel an HTTP request using the takeUntil operator with an RxJS Subject.
Method : Using takeUntil
import { HttpClient } from '@angular/common/http';
import { Component, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
})
export class ExampleComponent implements OnDestroy {
private destroy$ = new Subject<void>();
constructor(private http: HttpClient) {}
fetchData() {
this.http.get('https://api.example.com/data')
.pipe(takeUntil(this.destroy$))
.subscribe(response => {
console.log(response);
});
}
cancelRequest() {
this.destroy$.next(); // Cancels the ongoing request
this.destroy$.complete();
}
ngOnDestroy() {
this.cancelRequest();
}
}