gpt4 book ai didi

javascript - 减少 Angular JS 实时 ajax 请求的消耗

转载 作者:行者123 更新时间:2023-12-02 14:43:49 24 4
gpt4 key购买 nike

我有一个实时数据库搜索,其中我绑定(bind)了变量 $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>

Controller :

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>

关于javascript - 减少 Angular JS 实时 ajax 请求的消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36771629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com