角度达到 10 次 $digest() 迭代

angular 10 $digest() iterations reached

本文关键字:digest 迭代      更新时间:2023-09-26

>我遵循 thinkster MEAN 堆栈教程,我在角度工厂服务中遇到了问题

角度.js:11598 错误: [$rootScope:infdig] 10 次 $digest() 迭代 达到。中止!观察者在过去 5 次迭代中触发:[]

应用.js

app.factory('posts', ['$http', function($http){
    var o = {
        posts: []
    };
    o.getAll = function() {
        return $http.get('/posts').success(function(data){
            console.log(data)
            angular.copy(data, o.posts);
        });
    };
    return o;
}]);

我的配置文件具有路由提供程序

$stateProvider
    .state('home', {
        url: '/home',
        templateUrl: '/home.html',
        controller: 'MainCtrl',
        resolve: {
            post: ['$stateParams', 'posts', function($stateParams, posts) {
                return posts.get($stateParams.id);
            }]
        }
    })

我不确定出了什么问题。

任何帮助都非常感谢。提前感谢...

.success已弃用,所以我将使用then

我想这就是你想写的。

app.factory('posts', ['$http', function($http){
    var o = {}; 
    o.get = function(id){
        return $http.get('/posts/'+id).then(function(response){
            return response.data;
        });
    }
    o.getAll = function() {
        return $http.get('/posts').then(function(response){
           return response.data;
        });
    };
    return o;
}]);

 resolve: {
        post: ['$stateParams', 'posts', function($stateParams, posts) {
            return posts.get($stateParams.id);
        }]
    }
// usage of the factory in controller : 
    posts.getAll().then(function(posts){
         $scope.allPosts = posts;
    })
    posts.get(id).then(function(post){
        $scope.post = post;
    })

几点:

  1. then/success是可链接的;但是您必须按顺序使用 return 语句,以便下一个链具有数据。我会得到你归还的东西。
  2. 我完全不知道你从哪里得到你的return posts.get($stateParams.id);所以我添加了一些相关的东西。