Stijn Geukens
Stijn Geukens

Reputation: 15628

$resource; how to encapsulate API methods

I have following angularjs service that exposes some methods to execute REST requests.

managerApp.factory('parameterService',
    function($resource){
        return {
            findAll:    $resource('rest/globalparam/list'),
            getByName:  $resource('rest/globalparam/getByName/?name=:name'),
            update:     $resource('rest/globalparam')
        };
    }
);

This is used as following:

$scope.parameters = parameterService.findAll.query();
$scope.selectedParameter = parameterService.getByName.get({name: $routeParams.id});

Although this works fine I'm not so happy about both the syntax and the fact that I need to know about the $resource API (query(), get()) in my controller. What I would like to see in my controller is:

$scope.parameters = parameterService.findAll();
$scope.selectedParameter = parameterService.getByName($routeParams.id);

This would make unit testing (mocking the service) a lot easier as well.

This is probably more a JavaScript than an AngularJS question.

Is this possible and how?

Upvotes: 1

Views: 315

Answers (1)

Parv Sharma
Parv Sharma

Reputation: 12705

what you can do differently is to return functions from factory instead of a promise/resource object

managerApp.factory('parameterService',['$resource',
    function($resource){
    var findAll = function(){return $resource('rest/globalparam/list').query(); }        
    return {
            findAll : findAll
        };
    }]
);

Upvotes: 3

Related Questions