使 Angular JS 实时 ajax 请求消耗更少
make Angular JS real time ajax requests less consuming
我有一个实时数据库搜索,我绑定变量$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; }
相关文章:
- ajax请求的顺序总是不同的
- 从ajax请求中获取javascript对象
- Ajax请求文档就绪会导致jquery加载缓慢
- MockJax没有在JavaScript应用程序中发送对我AJAX请求的响应
- 正在传递JSONP标头's数据参数到另一个文件中的AJAX请求
- JavaScript代码未正确检查ajax请求
- node.js请求数据事件未在CORS ajax调用中触发
- jQuery Ajax GET请求工作不正常
- "日期“;AJAX请求返回的类型值未定义
- Django - 响应请求 AJAX
- 使用 jQuery 的 CORS 请求 - $.ajax()
- 如果无线电值为 ==1,则请求 ajax
- 如何处理对循环中发出的多个异步请求(AJAX 调用)的响应
- POST请求ajax jquery错误
- CasperJS don'我没有请求AJAX
- 使用这种Facebook风格的Lightbox-请求AJAX-在一个页面上覆盖多个按钮
- 400错误请求ajax post请求
- 如何在开始发送请求ajax之前延迟3秒
- 与jQuery同时请求AJAX
- 使用POST请求AJAX发送json对象