Angular button click destroys any APIs previously called

In the project I'm working on, there is a search button that triggers an API call when clicked. I want to ensure that if the button is clicked again while the previous API call is still in progress, the previous call will be cancelled and only the most recent API call will stay active. How can I achieve this functionality using TypeScript? Currently, I am attempting to use ngDestroy() when clicking the button, but it seems that this approach is not effective.

Answer №1

ngOnDestroy is a method triggered by Angular when a component is being destroyed (such as when the route changes or a ngIf condition is met). It is important to note that you should never manually call this method.

Instead of manually handling the cancellation of API calls, you can utilize the powerful switchMap operator provided by RxJS. This operator automatically cancels any previous observable when a new emission is received. In the context of triggering actions with a button click, you can set up a subject like so:

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

public ngOnInit(): void {
   this.submitSource.pipe(
     switchMap(() => this.someService.someApiCall()
   ).subscribe(result => {
    // Handle the result of the API call
   });
}

public buttonClick(): void {
   this.submitSource.next(null);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered when pushing Angular data to Django for user login form: 'Unexpected token < in JSON at position 2' while attempting to parse the JSON

I believe the < symbol is appearing because the response is in HTML or XML format. This is the section of my code where the login process is failing. public login(user) { this.http.post('/api-token-auth/', JSON.stringify(user), this.ht ...

What is the best way to choose a particular radio button from a group of radio buttons using typescript?

Is there a way to automatically select a specific radio button when an item is chosen from a dropdown menu on the webpage using a TypeScript function that is triggered by the dropdown selection? ...

Derive the property type based on the type of another property in TypeScript

interface customFeatureType<Properties=any, State=any> { defaultState: State; properties: Properties; analyzeState: (properties: Properties, state: State) => any; } const customFeatureComponent: customFeatureType = { defaultState: { lastN ...

ngx-emoji-mart customBackgroundImage directive

Currently, I am integrating ngx-emoji-mart with Angular 6 and encountering an issue with the backgroundImageFn directive. The ngx-emoji-mart documentation suggests using the directive to load the emoji sheet locally like this: <emoji-mart [backgroundIm ...

Exploring the world of chained JavaScript Promises for automatic pagination of an API

Dealing with a paged API that requires fetching each page of results automatically has led me to construct a recursive promise chain. Surprisingly, this approach actually gives me the desired output. As I've tried to wrap my head around it, I've ...

What prevents `console.log` from working within a button click event?

Why is this not functioning correctly? <button (click)="console.log('ok');">Display Details</button> The error message reads: Cannot read property 'log' of undefined However, a console.log statement in the class construc ...

How to effectively utilize the Angular Material Button individually in a Stackblitz environment?

Most of the time, I rely on Angular Material when working on Stackblitz. Usually, I just import a comprehensive module and everything functions smoothly. However, I recently attempted to solely import the Angular Material Button Module and encountered thi ...

Using TypeScript with .env file variables: a step-by-step guide

I stored my secret jwt token in the .env file. JWT_SECRET="secretsecret" When I attempt to retrieve the value using process.env.JWT_SECRET, I encounter an error: Argument of type 'string | undefined' is not assignable to parameter of t ...

Using an Angular2 directive within the <head> element

How can I use my custom image directive to load the favicon in my index.html file? <head> <link rel="shortcut icon" [my_directive]="path to image"/> ... </head> <body> <div class="content"></div> </body ...

Avoiding non-router links from remaining active while using routerLinkActive in Angular

One component in the list item of the navigation bar caught my attention: <div [routerLink]="link" routerLinkActive="bg-blue-100" class="flex w-[80%] mx-auto p-3 rounded-md font-bold text-xl justify-between items-center gr ...

How do you switch the chart type by clicking on the dropdown menu in Angular and TypeScript, using Highcharts?

Struggling to figure out how to change the chart type in an Angular component typescript file when clicking on a dropdown. Here's what I have so far: Any ideas why it's not working? onOptionsSelected(value:string){ console.log("the sele ...

Is it possible to both break down a function parameter and maintain a named reference to it at the same time?

When working with stateless functional components in React, it is common to destructure the props object right away. Like this: export function MyCompoment({ title, foo, bar }) { return <div> title: {title}, ...</div> } Now ...

suspicion arises that the argument is not correctly referencing the appropriate variables

I am trying to grasp the situation happening here. I have two variables activeToInactive and inactiveToActive which I increase whenever a status is updated. Here's my code snippet: Counter Service: export class CounterService { // Initial States ...

Analyzing feedback according to the ResponseHeaders

When sending a request to a REST API using http.get(), the response headers usually contain metadata related to page number, total results, and page count. Angular's HttpClient handles parsing and returning data from the response.body in an Observabl ...

What is the mechanism behind flatMap executing code in a synchronous manner?

Currently, I am utilizing flatMap because it has the ability to process asynchronous code synchronously, allowing values from previous results to be handled one-by-one. However, I am unsure of how this functionality is achieved since the documentation does ...

Tips for customizing the appearance of a specific mat-button component in an Angular project

In my Angular application, I have set up a scenario where users are presented with multiple choices through buttons. When a user clicks on a button, a specific component is displayed based on their choice. I am currently working on enhancing the styling of ...

Modifying the color of the chosen item - ion-select

Can anyone help me with changing the color of the selected item on ion-select? I've tried several solutions without success. Any suggestions? Documentation: https://ionicframework.com/docs/api/select I attempted to use the color property, but it did ...

Typescript fails to recognize a value assigned within an await statement

Looking at the code snippet below, we see that the variable x starts off undefined and can later be assigned a value of 1 within an `await` promise. Despite setting x to 1 inside the awaited promise, TypeScript still perceives it as undefined after the pr ...

There was an issue trying to access the 'img' property of an undefined value in JSON data

I have successfully generated a JSON file containing data. Through the use of a provider in Ionic 3, I have managed to fetch the data. Below is the content of the JSON file [ { "teachers": { "img":"assets/home/img.png" } ...

Tips for maintaining the settings of ag grid gridOptions

Is there a way to preserve the state of various ag grid features such as filtering, sorting, column order, and tool panel pivoting? I am aware that the necessary state is stored in gridOptions.api and gridOptions.columnApi. However, when navigating to othe ...