1

I following thinkster MEAN stack tutorial and I have a problem in angular factory service

angular.js:11598 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: []

app.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;
}]);

my config file has route provider

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

    })

Im not sure what is wrong..

Any help is much appreciated. Thanks in advance...

Coeus
  • 2,385
  • 3
  • 17
  • 27
  • 1
    Could you check out this answer, probably you have something wrong with the logic in template? [10 $digest error](http://stackoverflow.com/questions/17116114/how-to-troubleshoot-angular-10-digest-iterations-reached-error) – Kanso Code Apr 22 '16 at 09:13
  • there is missing method `.get()` in **posts factory**. You've mixed `.get()` with `.getAll()` - please read tutorial more carefully. – Krzysztof Safjanowski Apr 22 '16 at 09:14
  • Could you please give us more info or code you use ? Couldn't see any potential issue from the code above, the `$digest error` mostly happen upon `$watchers` in directive or html template – David Tao Apr 22 '16 at 10:59

1 Answers1

0

.successis deprecated so i will use then

I think this is what you wanted to write.

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;
    })

Some points :

  1. then/ successare chainable; however you must use the return statement in order than the next chain will have the data. I will have what you have returned.
  2. I totally don't know from where you got your return posts.get($stateParams.id); so i added something relevant.
Walfrat
  • 5,363
  • 1
  • 16
  • 35