Judo
Judo

Reputation: 5247

Passing Parameters to AngularJS $http Factory

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?

Upvotes: 1

Views: 4448

Answers (1)

Dayan Moreno Leon
Dayan Moreno Leon

Reputation: 5435

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

Upvotes: 3

Related Questions