At times, the AngularJS HTTP GET request upon key press may not always fetch the most up-to-date

I am developing a small application that triggers the following function on a keyup event. The issue I am facing is that if I type quickly, the last key press may not be the latest dataset because the promise removes all previous data from the array and replaces it with the new data.

For example:

Request 1 - 150ms Request 2 - 80ms

In this scenario, Request 1 overwrites all values of Request 2, resulting in outdated data based on the most recent key press.

Does anyone know a solution to this problem? Here is my code below:

Javascript:

app.controller('FlagsController', function ($scope, $http, $location, $window, $timeout) {

$scope.Products = []

$scope.GetRecords = function () {
    try {
        console.log('Get Records')
        // Simple GET request example with promise: To get FeatureRelations
        $http({
            method: 'GET',
            url: 'GetFeatureRelations.ashx?SearchQuery=' + $scope.SearchTerm
        }).then(function (res) {
            $scope.Products = []
            for (var i = 0; i < res.data.length; i++) {
                $scope.Products.push(res.data[i])
            }
            $scope.busy = false
            $scope.showLoader = false
        }, function (error) {
            console.error(JSON.stringify(error))
            $scope.busy = false
            $scope.showLoader = false
        })
    }
    catch (ex) {
        console.error("Error: " + ex.toString())
    }
}
})

HTML:

<input type="search" ng-keyup="GetRecords()" class="form-control" style="width: 30%" ng-model="SearchTerm" placeholder="Search Product Code, Name or Brand...">

Answer №1

If you need to cancel the previous $http request when the method is called again, you can inject $q and create a canceler promise.

var canceler;
$scope.RefreshData = function () {
    try {
        if (canceler) {
            canceler.resolve();
        }
        console.log('Refreshing Data')
        // Example of a simple GET request with promise: Retrieving FeatureRelations
        canceler = $q.defer();
        $http({
            method: 'GET',
            url: 'GetFeatureRelations.ashx?SearchQuery=' + $scope.SearchTerm,
            timeout: canceler.promise
        })
//...

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

Using Ansible's RAW module for leveraging Curl commands and JSON files in a Kubernetes environment

How can I use curl to parse a JSON attribute named keys_base64 in Ansible's raw module due to a network issue? Despite trying various approaches, I am still unable to get it to work. Update: Solution Found Original Post ** Example of JSON Keys Obje ...

Which is better for scrolling in Angular 2+: using HostListener or window.pageYOffset?

Which syntax is best for maximizing performance in Angular 2+? Is it necessary to use HostListener, or is it simpler to obtain the scroll position using the onscroll window event and pageYOffset? @HostListener('window:scroll', ['$event&ap ...

Selecting multiple input elements in Jquery without relying on IDs

I am working with the following block of code: <div class="container"> <div class="row"> <div class="col"> <input class="form-control" type="text" id="#first"> </div> <div class="co ...

Tips for avoiding redundant AJAX requests

Currently, I am working with JavaScript and not jQuery. Imagine a scenario where I have 3 users in my database [Kim, Ted, Box] and 3 buttons structured as follows: <button class="user">Kim</button> <button class="user">Ted</button> ...

Ways to send data to a popup in svelte

Hey there, I could really use some assistance with my Svelte app. I'm trying to implement a modal and pass a parameter to the modal component in order to customize its content. However, when using the open() function of Modal, we only need to provide ...

Issue with Access Denied Error in Internet Explorer 11 when Using AngularJS

Every software development process consists of two essential components. FIRST, the hard work of developing the application. SECOND, the even harder task of making it compatible with the notorious Internet Explorer. Currently, we have an AngularJS (v1.3.1 ...

Is my JQuery width() function giving incorrect value results?

Currently, I am facing a situation similar to the following: We have two popup windows that are quite alike. These popups are generated by a factory in JavaScript, allowing them to share common events and functions. One such function is our custom resize ...

Sending values from multiple radio groups in JavaScript can be done by accessing each group individually and extracting

This is an add to cart system. Currently, I am able to send quantity with an ID. However, I also want to send radio group values. How can I achieve this? Here are my codes: product.php <script> jQuery(function ($) { $('.popbutton').on(&a ...

Having trouble with Web API 2 not accepting JSON requests?

In the MVC Web API controller, there seems to be an issue with the JSON request parameter when it contains square brackets [ ]. The headers are set to accept application/json type. Sample Request Object Definition public class Sample { public int Id ...

Guide to parsing unprocessed JSON into a specified format including a Date field

I need help figuring out how to import a raw JSON data file and automatically convert my date string to a date object within my type. In my type definition: export type Client = { id: number; first_name: string; last_name: string; dob: Dat ...

Transform a personalized Google map into a visual representation

I am facing a challenge with the following issue. I have implemented a custom overlay on a Google map and it works perfectly in the browser. However, my dilemma arises when I need to display an image with a marker for each point of interest on a different ...

What is the best way to extract a single String element from a List<MyList> Array list?

I have been working on implementing a RecyclerView where I retrieve data from an API in JSON format. To achieve this, I created two models - one for my RecyclerView data and the other for my calendar view. The data retrieval for the RecyclerView using a cu ...

Remove class names from CSS and store them in an array

I have a specific HTML file where the CSS is included at the beginning of the document, enclosed within comment tags. My task is to extract the names of the classes located between these comment tags. /* target >> */ .oneClass { ... } .anotherOne { ...

The Model Viewer module is unable to load the three-dimensional model

Attempting to incorporate a 3D model into my website using the modelviewer library, but encountering difficulties in loading the file as shown below: Just to note, I am utilizing github pages with a custom domain from godaddy which may be contributing to ...

Absolute file path reference in Node.js

I'm working on a Node.js project using WebStorm IDE. Here's the structure of my project: The root folder is named "root" and inside are 2 folders: "main" and "typings". The "main" folder has a file called "foo.ts", while the "typings" folder co ...

Implementing automatic redirection upon clicking using React without the need for manual clicking

I'm experiencing an issue where the page seems to automatically navigate to another page without clicking on the div. Can anyone explain why this is happening? Here's the code snippet for reference: import React, { Component } from "react&q ...

Validation failed for the WebAPI OData request, and the ModelState object was not returned

I am currently developing an AngularJS web form to execute a POST request (insert) into a table utilizing WebAPI configured as OData. My objective is to receive a failed validation ModelState object back in JSON format, so I can validate the appropriate fi ...

Utilizing Jquery for efficient event delegation across various elements and events

I need to ask my question quickly because my English is not very good. Is it possible for me to use delegate in this way or is there a similar alternative? $( 'body ').delegate({ 'input[type=text]': { 'change' ...

Using Python to transform a nested dictionary list into a Pandas Dataframe

I have come across the following dictionary structure test = {'data': [ {'actions': [ {'action_type': 'link_click', 'value': '16'}, {'action_type': 'post_engagement', ...

Utilizing jQuery, the code can modify a basic element on a webpage by extracting JSON data from two external device buttons

This project I'm working on for school is quite simple. I am trying to change the background color of a webpage and more with the use of an external device that has two buttons (microbit a and b) connected to a serial port. The device writes data stri ...