AngularJS在$http请求返回错误时创建无限循环
我的问题很简单,但我不知道会发生什么 我想做的就是从我的本地RESTAPI读取所有帖子。当我从API响应HTTP401时,AngularJS在无限循环中不断重复GET请求AngularJS在$http请求返回错误时创建无限循环,angularjs,http,Angularjs,Http,我的问题很简单,但我不知道会发生什么 我想做的就是从我的本地RESTAPI读取所有帖子。当我从API响应HTTP401时,AngularJS在无限循环中不断重复GET请求 var request = { method: 'GET', url: 'http://jentzschserverdev-46690.onmodulus.net/index.php/issues', headers: { 'Anonymous': tru
var request = {
method: 'GET',
url: 'http://jentzschserverdev-46690.onmodulus.net/index.php/issues',
headers: {
'Anonymous': true
}
};
$http(request)
.success(function(data){
console.log('success', data);
deferred.resolve(data.issues);
})
.error(function(){
console.log('error');
deferred.resolve([]);
});
控制台告诉我:
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.3.15/$rootScope/infdig?p0=10&p1=%5B%5D
at angular.js:63
at Scope.$digest (angular.js:14346)
at Scope.$apply (angular.js:14571)
at done (angular.js:9698)
at completeRequest (angular.js:9888)
at XMLHttpRequest.requestLoaded (angular.js:9829)(anonymous function)
@ angular.js:11655(anonymous function) @ angular.js:8596Scope.$apply
@ angular.js:14573done @ angular.js:9698completeRequest
@ angular.js:9888requestLoaded @ angular.js:9829 angular.js:63
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.3.15/$rootScope/infdig?p0=10&p1=%5B%5D
为了更好地理解,我创建了一个plunker:
(如果取消对app.js中的代码的注释,您的浏览器将因无限循环而崩溃)
有谁能告诉我这里发生了什么以及为什么???当作用域上的一个对象是时,一个无限的摘要在角度上发生。如果没有看到更多的代码,我们无法确定是什么导致了这一点 不确定这是否导致您的问题,但您当前的
$http.get
未正确处理错误,即http 401
您需要这样做:
$http.get('http://mylocalapi/posts').then(
function(success) {
console.log('RESPONSE', success);
}, function(error) {
console.log('ERROR', error);
});
then()
方法接受两个参数,一个成功回调和一个错误回调
更新
查看我对您的网站的更新
无限摘要似乎来自于在您的ngRepeat中使用一个函数:
<li class='issue' ng-repeat="issue in loadIssues()">
{{issue.name}}
</li>
另外,$http
本身返回一个承诺,因此您不需要使用$q
。只需将作用域上的数组指向已解析的数据:
$http(request)
.success(function(data){
console.log('success : ', data);
$scope.issueList = data;
}).error(function(error) {
console.log('error : ', error);
});
它没有触发get请求。您正在更改模型,angular正在达到脏检查算法的限制,但我没有访问任何$scope,请求被激发,我可以在网络选项卡中看到它创建一个plunker或fiddle,以便我们可以解决它。:-)这段代码不会导致无限循环,但您可能有一些代码作为导致无限循环的失败http请求的结果作出反应。我们需要更多的代码来解决这个问题。我将创建一个plunker,谢谢,欢迎来到so!这是一个很好的第一个答案。哦,我们需要更多的细节。我在描述中添加了一个plunker链接above@MatthiasPosch我用一个新的plunker链接更新了我的答案。谢谢你,这就是问题所在…多大的一个noob错误:/
$http(request)
.success(function(data){
console.log('success : ', data);
$scope.issueList = data;
}).error(function(error) {
console.log('error : ', error);
});