1

I created a factory for $http as below

TestApp.factory('TestHttpFactory', function ($http) { 
    return $http({
        method: 'GET',
        url: 'http://www.domain.com/api/get_item/?item_id=:id',
        params: { id: '@id' }
    });
});

In the controller I need to get the value returned by the API (as below). To get the data and use it in code I am using the success method which works fine:

var MyCtrl = function ($scope, $location, $http,   $routeParams,  TestHttpFactory) {

    TestHttpFactory
        .success(function (data) { 
            $scope.item =  data;
            //do something with $scope.item
    }); 
};

However, I am unsure of how to pass a parameter to the factory, the below fails with the error : object is not a function.

TestHttpFactory({id : $routeParams.id})
        .success(function (data) { 
            $scope.item =  data; 
    }); 

How should I pass the parameters to the factory?

1 Answer 1

3

you cant since you are taking an invoked function. lets refactor your 'Factory'/Service

TestApp.factory('TestHttpFactory', function ($http) { 
    return function(id){
         return $http({
            method: 'GET',
            url: 'http://www.domain.com/api/get_item/?item_id=:id',
           params: { id: id }
         });

    }
});

then in your controller you can do

var MyCtrl = function ($scope, $location, $http,   $routeParams,  TestHttpFactory) {

    TestHttpFactory(1234)
        .success(function (data) { 
            $scope.item =  data;
            //do something with $scope.item
    }); 
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, so if I understand correctly, originally the return was not an $http object but rather the invoked $get method on the $http object.
correct $http is the service $http() is the service invocation that returns a specific type of deferred with the succes and error methods at that point the $http request has already been made, you can not alter it so you needed to either get your hand on the actual $hht from your cotnroller and make the call from there or use a proxy function that takes aparmeter and makes the call for you. this is actually kind of what the $resource service do, you should probably look into that if you don't require the low level handling that $hhtp provides

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.