AngularJS对key up的HTTP GET请求有时返回的不是最新的数据集

AngularJS HTTP GET request on key up sometimes returns not the latest dataset

本文关键字:返回 数据集 最新 请求 key up HTTP GET AngularJS      更新时间:2023-09-26

我正在构建一个小应用程序,在keyup事件上执行以下函数,唯一的问题是,如果我键入快速,那么最后一次按键可能不是最新的数据集,因为承诺从我拥有的数组中删除所有数据并插入新数据。

但是,如果我执行以下操作

请求1 - 150ms请求2 - 80ms

然后请求1删除所有请求2的值并插入请求1的值,因此根据最后一次按键,数据不是最新的:(

有人知道解决这个问题的方法吗?我的代码如下:)

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...">

您可以在再次调用该方法时取消先前的$http请求。注入$q并创建一个取消承诺

var canceler;
$scope.GetRecords = function () {
    try {
        if (canceler) {
            canceler.resolve();
        }
        console.log('Get Records')
        // Simple GET request example with promise: To get FeatureRelations
        canceler = $q.defer();
        $http({
            method: 'GET',
            url: 'GetFeatureRelations.ashx?SearchQuery=' + $scope.SearchTerm,
            timeout: canceler.promise
        })
//...