[SOLVED] Destroy previously calling APIs on button click in Angular


I have a search button in my project upon clicking it, an API is called. If I click the button again the previously called API will be destroyed and only the newly called API will exist. How can I do this in typescript? I am calling ngDestroy() while I click the button. However, it seems it is not working.


ngOnDestroy is called by Angular when a component is destroyed (due to changing route, ngIf condition, etc.). You should never call it yourself.

You just need to cancel the previous API call; which RxJS does quite well with the switchMap operator. This operator will cancel any previous observable when a new emission is given to it. Since you’re triggering off a button click, you’ll just need to setup a subject:

private submitSource: Subject<void> = new Subject();

public ngOnInit(): void {
     switchMap(() => this.someService.someApiCall()
   ).subscribe(result => {
    // Use the API call result

public buttonClick(): void {

Answered By – BradleyDotNET

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *