角js无穷大迭代误差



我在运行angularjs调用rest服务时遇到一个错误。详细信息如下。

这是我的app.js代码:

angular.module('myApp', []);
angular.module('myApp').factory('weatherService',function($http){
return {
getWeather:function(city,country){
var query = 'city=' + city + '&country=' + country;
return $http.get('http://api.openweathermap.org/data/2.5/weather',{
params: {
q:query
}
}).then(function(response){
return response.data.weather[0].description;
});
}
}
});
angular.module('myApp').controller('WeatherController',
function($scope,weatherService){
$scope.getWeather=function(city,country){
$scope.WeatherDescription = "Fetching...";
weatherService.getWeather(city,country).then(function(data){
$scope.weatherDescription = data;
}, function(data){
$scope.weatherDescription = "Could not obtain data";
});
}
});

html代码:

<html ng-app="myApp">
<script src="../js/angular/angular.js" ></script>
<script src="../js/app.js" ></script>
<body ng-controller="WeatherController">
{{getWeather('chicago','usa')}}
</body>
</html>

我在页面上得到一个空白回复。当我打开控制台时,我得到这个错误:

Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.3.13/$rootScope/infdig?p0=10&p1=%5B%5D
at angular.js:63
at Scope.$digest (angular.js:14281)
at Scope.$apply (angular.js:14506)
at done (angular.js:9659)
at completeRequest (angular.js:9849)
at XMLHttpRequest.requestLoaded (angular.js:9790)
(anonymous) @ angular.js:11607
(anonymous) @ angular.js:8557
$apply @ angular.js:14508
done @ angular.js:9659
completeRequest @ angular.js:9849
requestLoaded @ angular.js:9790
angular.js:63 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!

可能出了什么问题?有人能帮忙吗?我使用的是1.6.1版本的

谢谢。

这与角度$digest循环的工作方式以及表达式的求值方式有关。

您的HTML中有一个表达式{{getWeather('chicago','usa')}}。每当出现$digest循环时,就会对该表达式进行求值,并调用该函数。

该函数设置一个值$scope.WeatherDescription = "Fetching...";,然后调用一个异步函数。CCD_ 5中的变化随后引起新的CCD_ 6迭代。新的$digest迭代遇到表达式,并(再次)启动函数。即使数据从promise返回,将导致$scope上的属性更改,这将导致(另一个)$digest,导致对函数的(另一!)调用。。。这基本上将无限发生,这就是为什么angular在10个周期后自动抢占处理。

有时可以在表达式中触发函数调用,但为了实现这一点,函数调用需要返回一个值,并且不需要触发对$scope上与表达式无关的另一个属性的更改。

在您的情况下,您不希望使用$scope.WeatherDescription,而是希望return服务的承诺。

您可以通过检查$scope.$$phase来检查$digest是否已经在进行中。

weatherService.getWeather(city,country).then(function(data){
if(!$scope.$$phase) {
$scope.weatherDescription = data;
}
}, function(data){
if(!$scope.$$phase) {
$scope.weatherDescription = "Could not obtain data";
} 
});

最新更新