0

I have a Service and a Controller. The controller calls a function, getItems() on the Service. The Service returns an array of data.

However, the controller appears to not be receiving this, oddly enough.

Controller:

ItemModule.controller('ItemController', ['$scope', 'ItemService',
    function ($scope, ItemService) {

        $scope.items = [];

        $scope.getItems = function() {
            $scope.items = ItemService.getItems();
        }

        $scope.getItems();

    }
]);

Service:

ItemModule.service('ItemService', ['$rootScope', '$http', 
    function($rootScope, $http) {

        this.getItems = function() {
            $http.get($rootScope.root + '/products').success(function(data) {
                // This prints it out fine to the console
                console.log(data);
                return data;
            });
        }

    }
]);

What am I doing wrong?

Patrick Reck
  • 11,246
  • 11
  • 53
  • 86
  • 1
    `$http.get` is asynchronous and `success` is a callback. `return`ing from it is wrong (does not do what you expect it to). Please read this: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call#answer-14220323 – Sergiu Paraschiv Nov 14 '13 at 11:05
  • 2
    Your problem would be solved for now by returning the HTTP promise, i.e.: `return $http.get(...existing code without change...)` – Nikos Paraskevopoulos Nov 14 '13 at 11:17
  • also not returning object you create in service, so when call `ItemService.getItems();` should see error that the method is undefined – charlietfl Nov 14 '13 at 12:43

1 Answers1

0

A quick and dirty fix would be like that:

ItemModule.service('ItemService', ['$rootScope', '$http', 
function($rootScope, $http) {

    return {
        getItems : function(scope) { 
            $http.get($rootScope.root + '/products').success(function(data) {
                scope.items = data;
            });
        }
    }

}
]);

and then in your controller just call:

 ItemService.getItems($scope);

But if your controller is a part of route (and probably is) it would be much nicer to use resolve (look here).

Community
  • 1
  • 1
artur grzesiak
  • 20,230
  • 5
  • 46
  • 56