1

I am using a service inside an angular controller like so: my Service:

MyServices.factory('Product', ['$http',function($http){

    this.fn = function(city, state, category, categoryDetailValue) {
        return $http.get('serverURL',{params: {city:city, state:state, category:category, categoryDetailValue:categoryDetailValue}}
        ).then(function(results){
            return results.data;
        });
    };      
}]);

my Controller:

$scope.init = function () {
    console.log(Product);   
    Product.fn($rootScope.city, $rootScope.name, 'param1', 'param2').then(function(results) {
        // Do something with results
        $scope.items = results.Transactions;
    });

};

when i try to call the Service inside the controller, the error says "Product is undefined"; please correct me where is my mistake?

4
  • 2
    show the part of your controller when you inject the service Commented Aug 22, 2015 at 2:07
  • and i suppose that you are including the script when you have MyServices factory in your html Commented Aug 22, 2015 at 2:07
  • 1. You need to make sure you inject the service into the controller. 2. You are using .factory instead of .service, so you need to return an object with the public methods you want to expose from your service. Commented Aug 22, 2015 at 2:16
  • Could you to create a jsbin or plunkr with your code? Commented Aug 22, 2015 at 2:32

1 Answer 1

1

Use MyServices.service('Product',... instead of MyServices.factory('Product',

I think it is because a factory it is supposed to be a function that returns and object, and it is not called using new, so this is not what you think it is.

If you wanted to use a factory, it would be something like this:

MyServices.factory('Product', ['$http',function($http){
    return {
        fn : function(city, state, category, categoryDetailValue) {
            return $http.get('serverURL', {
                        params: {
                            city:city, 
                            state:state, 
                            category:category, 
                            categoryDetailValue:categoryDetailValue
                        }
            }).then(function(results){
                return results.data;
            });
        }
    };
}]);
Sign up to request clarification or add additional context in comments.

1 Comment

thank you vtortola, you spotted what my problem was. how would i write the function in the service, if i wanted to use " MyServices.factory('Product', " instead of "MyServices.service('Product',..."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.