当$ http请求返回错误时,AngularJS会创建无限循环

Mat*_*sch 2 http angularjs

我的问题很简单,但我无法找到发生了什么.

我想要做的就是阅读本地REST API中的所有帖子.当我从API响应HTTP 401时,AngularJS会在无限循环中不断重复GET请求.

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([]);
    });
Run Code Online (Sandbox Code Playgroud)

控制台告诉我:

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
Run Code Online (Sandbox Code Playgroud)

为了更好地理解我创建了一个plunker:http://embed.plnkr.co/R4tYUHei9vkylPgvAT5B/ (如果取消注释app.js中的代码,您的浏览器应该因无限循环而崩溃)

谁能告诉我这里发生了什么,为什么?

all*_*enx 5

当示波器上的对象始终发生变化时,会在角度发生无限摘要.如果没有看到更多代码,我们无法确定导致这种情况的原因.

不确定这是否导致您的问题,但您当前$http.get未正确处理错误,即您的HTTP 401

你需要做这样的事情:

$http.get('http://mylocalapi/posts').then(
    function(success) {
        console.log('RESPONSE', success);
    }, function(error) {
        console.log('ERROR', error);
    });
Run Code Online (Sandbox Code Playgroud)

then()方法有两个参数,一个成功回调和一个错误回调.阅读更多关于$ http的信息.

UPDATE

查看我对您的plunker的更新.

无限摘要似乎来自于使用ngRepeat中的函数:

<li class='issue' ng-repeat="issue in loadIssues()">
  {{issue.name}}
</li>
Run Code Online (Sandbox Code Playgroud)

$scope在ngRepeat 上创建数组并在其中使用它修复了:

<li class='issue' ng-repeat="issue in issueList">
  {{issue.name}}
</li>
Run Code Online (Sandbox Code Playgroud)

此外,$http返回一个承诺本身,所以你不需要使用$q.只需将范围上的数组指向已解析的数据:

$http(request)
  .success(function(data){
    console.log('success : ', data);
    $scope.issueList = data;
  }).error(function(error) {
    console.log('error : ', error);
  });
Run Code Online (Sandbox Code Playgroud)

  • 欢迎来到SO!这是一个很好的第一个答案.OP,我们需要更多细节. (2认同)