使 Angular JS 实时 ajax 请求消耗更少

make Angular JS real time ajax requests less consuming

本文关键字:请求 ajax Angular JS 实时      更新时间:2023-09-26

我有一个实时数据库搜索,我绑定变量$scope.city,html

<div class="col-lg-8">
    <div class="input-group">
     <span class="input-group-addon" id="basic-addon1">City@</span>
     <input type="text" ng-model="city" class="form-control" aria-describedby="basic-addon1">
    </div>
</div>

控制器:

app.controller('forecastController', ['$scope','varService','$http', function($scope,varService,$http){

$scope.city = varService.city;
$scope.days = 2;
$scope.$watchGroup(['days', 'city'], function() {   
        $http.get('http://api.openweathermap.org/data/2.5/forecast?q='+$scope.city+'&mode=json&appid=e652a2c384655ea24f5b12d2fb84c60f&cnt='+$scope.days+'&units=metric')
    .then(function(data) { $scope.forecast = data; });
  });
}]);

如您所见,每次$scope.city更改时都会$http.get()数据,但是它消耗了太多资源,我需要一个解决方案,它将在用户输入某些内容后每3-4秒调用一次$http.get,$timeout没有完成工作,请帮助,谢谢

在这种情况下,您需要一些自定义逻辑。就像当引发事件时$watchGroup,它需要停止执行一秒钟,在那一秒钟之后执行您的进程。

下面的示例步骤将为您提供帮助。

 <div data-ng-app="app">
     <div class="col-lg-8" data-ng-controller="appctrl">
         <div class="input-group">
             <span class="input-group-addon" id="basic-addon1">City</span>
             <input type="text" ng-model="city" class="form-control" aria-describedby="basic-addon1">
         </div>
     </div>
 </div>
<script>
    var app = angular.module('app', []);
    app.controller('appctrl', function ($scope, $http, $timeout) {
        $scope.city = "";
        $scope.days = 2;
        var filterTextTimeout;
        $scope.$watchGroup(['days', 'city'], function () {
            if (filterTextTimeout) $timeout.cancel(filterTextTimeout); // cancel all previous register watchGroup event
            filterTextTimeout = $timeout(function () {
                alert($scope.city); // in this place call you api for get the response
            }, 5000); // delay 
        });   
    });
</script>
您可以使用

ng-model-options来指定模型更改时的延迟。 然后,您可以使用ng-change触发函数来获取预测。

<input ng-model-options"{updateOn: 'default blur', debounce: { 'default': 4000, 'blur': 0 }}" ng-change="getForecast(city)" type="text" ng-model="city" class="form-control" aria-describedby="basic-addon1">

然后在控制器中:

$scope.getForecast = function(city) { $http.blahblahblah; }