Stop any ongoing search requests in Angular 7 using Ng2SmartTable

My current setup involves Angular version 7.0.1 and ng2-smart-table version 1.4.0. The issue I'm facing is that each search within the table triggers a new API request to fetch data. What I actually want is for only the latest search request to be processed, while canceling any previous pending requests.

Here is a snippet of my HTML code:

<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>

The class handling my data source:

export class DataSource extends LocalDataSource {

  protected conf: ServerSourceConf;
  private lastRequestCount = 0;

  constructor(conf: ServerSourceConf | {} = {}, private service: DataServiceService) {
    super();

    this.conf = new ServerSourceConf(conf);
    this.conf.totalKey = 'total';
  }

  count() {
    return this.lastRequestCount;
  }

  getElements(): Promise<any> {
    return this.requestElements().map(res => {
      this.lastRequestCount = this.extractTotalFromResponse(res);
      this.data = this.extractDataFromResponse(res);
      return this.data;

    }).toPromise();
  }

  // Other methods omitted for brevity...
}

Data-service.service:

import {Injectable} from '@angular/core';
import {environment} from '../../environments/environment';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataServiceService {

  url = environment.server;

  constructor(private http: HttpClient) { }

  getData(endpoint: string, options?: any) {
    return this.http.get(this.url + endpoint, {params: options}).pipe();
  }
}

Answer №1

Consider implementing the switchMap() method in your code, as it has the ability to cancel previous requests.

fetchElements(): Promise<any> {
    return this.retrieveElements().switchMap(res => {
      this.latestRequestCount = this.extractTotalFromResponse(res);
      this.data = this.extractDataFromResponse(res);
      return of(this.data);

    }).toPromise();
}

Are you using an older version of RxJS where you are not required to use the pipe() method? Your implementation might look something like this:

fetchElements(): Promise<any> {
    return this.retrieveElements().pipe(switchMap(res => {
      this.latestRequestCount = this.extractTotalFromResponse(res);
      this.data = this.extractDataFromResponse(res);
      return of(this.data);
    })).toPromise();
}

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

I am trying to figure out how to send a One Signal notification from my Ionic app using the One Signal REST API. I have reviewed the documentation, but I am still unable to understand it

Is there a way to send a one signal notification from my ionic app using the one signal API? I have reviewed the documentation but am having trouble with it. While I have set up the service and it is functional, I can only manually send notifications thr ...

NPM Package: Accessing resources from within the package

My Current Setup I have recently developed and published an npm package in typescript. This package contains references to font files located within a folder named public/fonts internally. Now, I am in the process of installing this package into an Angul ...

Reducing the Angular version from 11 to 9

{ "name": "project-learn-web", "version": "1.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", " ...

What is the process for navigating from one page to another in Ionic 2?

I am currently attempting to navigate between pages using ionic 2. I have been studying from the resources provided at https://ionicframework.com/docs/v2/api/navigation/NavController/ export class ApiDemoPage { constructor(public navCtrl: NavControlle ...

Transforming JavaScript into TypeScript within an Angular 4 component class

Here is the Javascript code I currently have. I need to convert this into a component class within an Angular component. As far as I understand, the Character.prototype.placeAt() code is used to add a new method or attribute to an existing object. In this ...

My Angular2+ application is encountering errors with all components and modules displaying the message "Provider for Router not found."

After adding routing to my basic app through app.routing.ts, I encountered errors in all of my test files stating that no Router is provided. To resolve the errors, I found that I can add imports: [RouterTestingModule], but is there a way to globally impo ...

Encountering MIME type error (text/html) during Angular project deployment

I am facing an issue while trying to deploy a project built with Angular/CLI 6.12.0. After transferring the content of the "dist" folder to a server, I encountered a console error related to MIME type. The module at address "http://www.sylvainallain.fr/p ...

Tips on designing unique field validation decorators in NestJS using GraphQL

I'm currently developing a NestJS API using apollo-server-express and have created an InputType for appointments as shown below: @InputType() export class AppointmentInput { @Field(of => String) @IsNotEmpty() name: string; @Field(o ...

The Angular Tooltip feature is unable to interpret the characters "' '" or "' '"

Let me explain the scenario: I am receiving a list of objects from my back-end service, which I then break apart using ngFor and display accordingly. Each item in the list has an associated toolTip that provides additional information. The info for each i ...

What's the best way to display a component once a function has been executed?

My service controls the visibility of components using *ngIf! Currently, when I click a button, the service sets to true and the components appear instantly! I want the components to only show after a specific function has finished executing. This means I ...

Currently, my goal is to upload a photo using Cloudinary's post API without relying on the Cloudinary SDK

Recently, I have been exploring the integration of cloudinary with Angular. In my quest to upload an image to cloudinary without using the SDK, I came across the option to do so via the post API. However, my attempts with the following code snippet were un ...

What is the primary purpose of the index.d.ts file in Typescript?

There are some projects that include all types declarations within the index.d.ts file. This eliminates the need for programmers to explicitly import types from other files. import { TheType } from './somefile.ts' Is this the proper way to use ...

Angular 2's color picker functionality

I'm looking to implement a color picker in my Angular 2 project. I attempted to use the npm library called angular2-color-picker, but after including the directive, all I could see was a blank screen (no errors in the console). Can someone please guid ...

IntelliJ is indicating a typescript error related to react-bootstrap-table-next

Working with react-bootstrap-table-next (also known as react-bootstrap-table2) has been causing a Typescript error in my IntelliJ environment, specifically on the validator field within my column definition. Despite trying various solutions, such as adding ...

What are the best strategies to troubleshoot issues during NPM Install?

I keep encountering errors during the npm install process, but everything works fine when I use npm install --force in my local environment. However, the issues persist during the repository build as my .yaml file script contains "npm install". Can anyone ...

Android layout featuring Ionic2 navbar with icons aligned on both sides at the top

<ion-header> <ion-navbar align-title="center" color="primary" hideBackButton> <ion-buttons ion-button icon-only start class="card-buttons"> <button class="card-buttons" (t ...

angular corresponding vue binding="$props"

If I wanted to take a shortcut, I could utilize v-bind="$props" to dynamically set key values as shown in the sample below : <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> ...

In Typescript, object strings can be enforced to be used from the parent object similar to

I am currently developing an API wrapper for a lower level library that utilizes enums to map human readable keys to internal values. In order to enhance security, I want to only use the enum keys and not the underlying values in any logging or other funct ...

Is there a way to merge two observables into one observable when returning them?

I'm struggling with getting a function to properly return. There's a condition where I want it to return an Observable, and another condition where I'd like it to return the combined results of two observables. Here is an example. getSearc ...

Angular Material (8) error code S2591: The variable 'require' is not defined in the current scope

Currently, I am attempting to record the date and time in the JavaScript console. Despite the code successfully logging the dates, an error message persists: Note: The code is functioning properly, with the dates being displayed in the console. It is only ...