AngularJS:为每个端点创建多个工厂?(AngularJS: Creating multiple factories for every endpoint?)

编程入门 行业动态 更新时间:2024-10-21 23:05:13
AngularJS:为每个端点创建多个工厂?(AngularJS: Creating multiple factories for every endpoint?)

以下一些例子,似乎我们可以注入一个工厂,它将包含一个这样的休息服务的端点

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

这看起来很棒,但是想像我有其他端点,即/ users /:id和/ groups /:id,你可以想像不同端点的数量会增加。

所以对于每个端点都有一个不同的工厂是好的做法,所以有..

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

还是有另一个推荐的方法?

我真的没有看到它的问题,但它会迫使我创建很多工厂,只是为了处理不同的端点。

任何帮助或指导真的很受赞赏

谢谢

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

最满意答案

这是一个偏好的问题。

但是没有什么可以阻止您将所有资源整合到一个工厂内,如:

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

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

                    
                     
          

更多推荐

本文发布于:2023-08-05 18:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1435764.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   工厂   AngularJS   Creating   endpoint

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!