To ensure that a new HTTP request is only sent after the completion of the initial request, all other requests made in the meantime should be ignored or cancelled

I am currently working on creating the front-end of a single page application using Angular2. The issue I am facing is that my database contains a large number of records and it runs very slowly, making it take up to 4-5 seconds to retrieve 10000 records (or even just the last 10 with an ORDER BY clause). Unfortunately, upgrading the database is not an option in this scenario.

My goal is to optimize the paginator so that when a user continuously clicks on the "next" button multiple times (let's say up to 100 times or more), only the first HTTP request is sent to the Server/API. Here is where I'm struggling:

I want to ensure that when the initial request returns with a result, any subsequent click events during that time are ignored until the last clicked event triggers a new request (excluding the requests made in between). If the user continues clicking, each subsequent click should reset the queue in order to send a fresh request. However, I have yet to figure out how to achieve this functionality.

I attempted to implement this using RxJS, but so far I've only managed to do it by employing intervals. Unfortunately, this approach results in all the requests being sent to the server if the user clicks too frequently. Below is a snippet of my current code:

 private clickStream = new Subject();

 ngOnInit() {
   this.clickStream
   .debounce(() => Observable.interval(600).take(1))
   .subscribe(
     params => {
       this.callHttpPostMethod();
     }
   );
 }

 onNextClick(event) {
     this.clickStream.next(event);
 }

If anyone has an Angular2 solution or alternative suggestions outside of RxJS for achieving this behavior, I would greatly appreciate the assistance. Thank you!

Answer №1

To ensure that only the most recent request is being handled, you can utilize the switchMap function in your code:

this.clickStream
    .debounceTime(500)
    .switchMap(e=> this.callHttpPostMethod())
    .subscribe(t=> {
          ... perform desired actions ...
     });

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

cdkVirtualFor failing to display complete list of items

Having a minor issue that I can't seem to figure out the cause of. My goal is to display a list from an observable (it contains 3 objects) However, only the first two items are showing up. When I use a regular list, all three of them appear. What cou ...

The Angular Material Table Collapse feature offers dynamic collapsing similar to jQuery Datatable

Is there a way to improve the appearance of my Angular Material Table, especially on mobile? https://i.stack.imgur.com/sZXPP.png The current display of my Angular Material Table is not aesthetically pleasing when viewed on mobile devices. https://i.stack ...

Ways to sidestep the rules set forth by tslint

Currently, I am facing an issue where I need a specific class to disable the max-classes-per-file restriction. I attempted to add the rule /* tslint:disable:max-classes-per-file: */ to the beginning of the file, but I still received the warning. Even af ...

ejs-lineargauge major divisions and minor divisions centered

I've been trying to align majorTicks and minorTicks in the middle of the axis, but so far I haven't found a solution despite searching and googling extensively. Here's a snippet of my code: majorTicks: { height: 12, interval: 1, width ...

Discovering the versatility of Typescript objects

I want to define a type that follows this rule: If the property container is present, then expect the property a. If the property item is present, then expect the property b. Both container and item cannot exist at the same time. The code I would expect ...

Exploring Angular2: Understanding how to retrieve an object with an unknown key

I am trying to showcase a specific value from different objects within a template. The path of the desired value depends on the object being referenced. For example: let obj = { "a": "a", "b": { "1": "1", "2": "READ ME" } } let ...

Oops! Looks like we encountered a problem: "Uncaught ReferenceError: process is not

As I work on my project utilizing angular 6 with Spring-boot, I have encountered an error that I am struggling to resolve. Specifically, the error message reads: Uncaught ReferenceError: process is not defined at Object../node_modules/util/util.js (ut ...

Can I pass mat-options to my custom mat-select component using ng-content?

I created a custom select component and attempted to utilize ng-content to pass in my options. Here is the code snippet I used: <lib-select [(selected)]="selected" (selectedChange)="onChange($event)"> <mat-option [value]="0">Value 1</ma ...

Error message "Webpack is encountering an issue stating you might require a suitable loader" appearing during React development using TypeScript

I've been struggling to set up a new project using webpack, react, and typescript. Despite my efforts, I can't seem to get it to work. I've experimented with the html loader and followed various tutorials to try and resolve the issue. Here ...

The selected data was inserted as a foreign key, leading to an Integrity constraint violation with SQLSTATE[23000]: 1048

Hello and thank you for joining us! I am currently working on a task that involves selecting the acc_id from the account_info table and inserting it as a Foreign Key into the patient_info table. Unfortunately, I have encountered an error: While testing ...

Why isn't Nodemon monitoring the directory in webpack-typescript-node.js?

Here are the contents of the package.json file for a TypeScript project using webpack and node.js: "scripts": { "build": "webpack", "dev:start": "nodemon --watch src --exec \"node -r dotenv/co ...

Grouping emitted events using RxJS in a Node.js environment

Currently, I am interfacing with a database and receiving the results in a continuous stream of events labeled 'db_row_received'. My aim is to categorize these results based on the company Id, however, I am encountering an issue where the subscri ...

AngularFire 2 dispatching email for password reset

I am looking to add a feature for resetting passwords or handling forgotten passwords using AngularFire2. It looks like the function sendPasswordResetEmail is either not available in AngularFire2 or the typings have not been updated yet. I tried accessing ...

When a dynamic formControl is added to a formArray, all mandatory inputs will automatically change color to red

Whenever a formcontrol is added, all necessary inputs will change to red. Take a look at my demonstration below: https://stackblitz.com/edit/angular-emman-sample?embed=1&file=src/app/app.component.html ...

NX combined with Nest.js and TypeORM, further enhanced with Webpack and Migrations

Recently, I embarked on a project using NX (Nest.js + Angular) and set up TypeORM for database configuration. While everything runs smoothly in "serve" mode, I found myself struggling with configuring migrations. In a typical Nest.js project, all files in ...

"Encountering a Prisma type error while attempting to add a new record

I am currently utilizing Prisma with a MySQL database. Whenever I attempt to create a new record (School), an error of type pops up in the console. Additionally, I am implementing a framework called Remix.run, although it does not seem to be causing the is ...

What is the significance of incorporating 'Actions' as data within the Redux framework?

According to Redux documentation, creating actions and action creators is necessary. Here's an example: function addTodo(filter) { return { type: SET_VISIBILITY_FILTER, filter } } Next step is to write reducers, like this: function t ...

Ensuring Typescript returns the accurate type depending on given parameters

i am working with a code example that looks like the following interface BaseQuestionType { label?: string } export type RadioQuestionType = BaseQuestionType & { radio: boolean } export type TextQuestionType = BaseQuestionType & { text: strin ...

Creating an interceptor to customize default repository methods in loopback4

Whenever I attempt to access the default repository code, I need to manipulate certain values before triggering the default crud function in the repository. How can I accomplish this? For example: ... @repository.getter('PersonRepository') priva ...

Dealing with Errors in Angular 5 using Observables: Why Observable.throw isn't working

Can someone assist with resolving this issue? Error message: core.js:1542 ERROR TypeError: rxjs__WEBPACK_IMPORTED_MODULE_3__.Observable.throw is not a function Software versions: Angular CLI: 6.0.8 / rxjs 6.2.1 import { Injectable } from '@angular/ ...