Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

angular resource - AngularJS: Creating multiple factories for every endpoint?

following some examples, it appears that we can inject a factory which would contain an endpoint for a rest service like so

services.factory('Recipe', ['$resource',
     function($resource) {
        return $resource('/recipes/:id', {id: '@id'});
}]);

This looks great, but imagine I have other endpoints i.e. /users/:id, and /groups/:id, as you can imagine the number of different endpoints are going to increase.

So it is good practice to have a different factory for each endpoint so having ..

services.factory('Recipe', ['$resource',............

services.factory('Users', ['$resource',.............

services.factory('Groups', ['$resource',...............

Or is there another recommended way ?

I really don't see an issue with it but its going to force me to create a lot of factories just for dealing with the different endpoints.

Any help or guidance really apprecaited

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's a matter of preference.

But nothing prevents you from consolidating all your resources inside one factory as in:

services.factory('Api', ['$resource',
 function($resource) {
  return {
    Recipe: $resource('/recipes/:id', {id: '@id'}),
    Users:  $resource('/users/:id', {id: '@id'}),
    Group:  $resource('/groups/:id', {id: '@id'})
  };
}]);

function myCtrl($scope, Api){
  $scope.recipe = Api.Recipe.get({id: 1});
  $scope.users = Api.Users.query();
  ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...