Search code examples
angularjsfactoryrestangularangular-promiseangularjs-factory

Cant get restangular factory to work


I'm sure it's something simple I'm missing here but I cant get this to work.. I want to use a factory so that I can reuse the data in multiple controllers.

(function() {
'use strict';

angular
    .module('www')
    .factory('profileFactory', profileFactory);

profileFactory.$inject = ['Restangular'];

/* @ngInject */
function profileFactory(Restangular) {

    var service = {
        getUserData: Restangular.one('/user/profile/').getList(),
        getFriendList: Restangular.all('api/users/getfriendsinvitations/').getList()
    };
    return service;

    }
})();

The controller:

(function() {
    'use strict';

    angular
        .module('www')
        .controller('ProfileController', ProfileController);

    ProfileController.$inject = ['profileFactory'];

    /* @ngInject */
    function ProfileController() {

      activate();

      function activate(profileFactory, $scope) {
       profileFactory.getFriendList.then(function (homeFriends) {
         $scope.homeFriends = homeFriends;
       });
      }
    }
})();

And I keep getting "TypeError: Cannot read property 'getFriendList' of undefined"

Edit: I have tried this as well, https://github.com/mgonto/restangular#decoupled-restangular-service, but no luck!


Solution

  • You factory is not defined correctly. In order to make available factory function to the service consumer, You should define factory that code in function, Also return that promise will help you to continue promise chain.

    Code

    function profileFactory(Restangular) {
    
        var service = {
            getUserData: function(){
               return Restangular.one('/user/profile/').getList();
            },
            getFriendList: function(){
               return Restangular.all('api/users/getfriendsinvitations/').getList();
           }
        };
        return service;
    }
    

    Controller

    (function() {
        'use strict';
    
        angular
            .module('www')
            .controller('ProfileController', ProfileController);
    
        ProfileController.$inject = ['profileFactory', '$scope'];
    
        /* @ngInject */
        function ProfileController(profileFactory, $scope) { //<==added dependancy here
    
          activate();
    
          function activate() {
           profileFactory.getFriendList().then(function (homeFriends) {
             $scope.homeFriends = homeFriends;
           });
          }
        }
    })();