angularjs - 如何正确地将 Controller 和服务从 AngularJS 转换为使用 ng-resource

标签 angularjs ngresource

我最近才开始学习 ng-resource。我想知道在将我的常规 AngularJS 应用程序转换为使用 ng-resource 的应用程序时,我是否走在正确的轨道上。

这是我的旧 home.js Controller (不使用 ng-resource):

angular.module("HomeApp", ["BaseApp"])
    .controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {

        var self = this;

        BaseService.fetch.posts(function() {
            self.posts = BaseService.posts;
            self.cerrorMessages = BaseService.cerrorMessages;
        });

        self.like = function(id, postType) {
            BaseService.like(id, postType, function() {
                self.cerrorMessages = BaseService.cerrorMessages;
            });
        };
    }]);

这是我的旧 base.js (基本服务):
angular.module("BaseApp", [])
    .factory("BaseService", ["$http", "$window", function($http, $window) {
        var self = this;
        self.posts = [];
        self.cerrorMessages = [];
        self.accessErrors = function(data) {
             self.cerrorMessages = [];
             for (prop in data) {
                 if (data.hasOwnProperty(prop)){
                     self.cerrorMessages.push(data[prop]);
                 }
             }
         };

        self.fetch = {
             posts: function(callback) {
                 $http.get('/posts/')
                 .then(function(response) {
                     self.posts = response.data;
                     callback();
                 }, function(response) {
                     self.accessErrors(response.data);
                     callback();
                 });
             }
         };

        self.like = function(id, postType, callback) {
            $http.post("/" + postType + "/" + id + "/like/")
            .then(function(response) {
                angular.forEach(self.posts, function(post, index, obj) {
                    if (post.id == id) {
                        post.usersVoted.push('voted');
                        post.voted=true;
                    };
                });
            }, function(response) {
                 self.accessErrors(response.data);
                 callback();
            });
        };

        return self;
    }]);

有人告诉我,我可以从使用 ng-resources 中受益匪浅,因为我有一个 RESTful 后端。我尝试转换上面的代码以开始使用 ng-resource,这就是我现在所拥有的。这是我的 resources.js :
angular.module('PostsResources', ['ngResource'])

.factory('PostsFactory', function($resource) {
  return $resource('/posts/:postId', { postId:'@id' });
});

.factory('PostLikeFactory', function($resource) {
  return $resource('/posts/:postId/like', { postId:'@id' });
});

这是我的 Controller ( home.js ):
angular.module("HomePageApp", ["BaseApp", "PostsApp"])
    .controller("MainCtrl", ["$http", "$window", "BaseService", "PostsResource", "PostLikeResource", function($http, $window, BaseService, PostsResource, PostLikeResource) {

var self = this;

function loadPosts() {
    self.posts = PostsFactory.query(function(data) {},
        function(error) {
          BaseService.accessErrors(error.data);
          self.cerrorMessages = BaseService.cerrorMessages;
        }
    );
};

self.like = function likePost() {
    PostLikeFactory.save(function(data) {
        angular.forEach(self.posts, function(post, index, obj) {
            if (post.id == id) {
                post.usersVoted.push('voted');
                post.voted=true;
            };
        });
    }, function(error) {
        BaseService.accessErrors(error.data);
        self.cerrorMessages = BaseService.cerrorMessages;
    }
)};

这是我的 BaseService ( base.js ):
angular.module("BaseApp", [])
    .factory("BaseService", ["$http", "$window", function($http, $window) {
        var self = this;
        self.posts = [];
        self.cerrorMessages = [];
        self.accessErrors = function(data) {
             self.cerrorMessages = [];
             for (prop in data) {
                 if (data.hasOwnProperty(prop)){
                     self.cerrorMessages.push(data[prop]);
                 }
             }
         };
        return self;
    }]);

我是否在将常规 AngularJS 应用程序转换为使用 ng-resource 的正确轨道上?在我看来,所需的代码量似乎相同。提前致谢!

最佳答案

我同意@Mark 的观点,您的 API 中可能没有足够的操作来充分利用 $resource,因此好处并不大。不过,对于你现在拥有的,如果你想使用 $resource,我会这样设置:

angular.module('PostsResources', ['ngResource'])
   .factory('Post', function($resource) {
      return $resource('/posts/:postId', { postId:'@id' }, {
         like: {
            url: '/posts/:postId/like',
            method: 'POST',
            params: { postId:'@id' }
         }
      })
   });

如果您到达每个端点使用多个操作的地方,我将拥有 Post 和 PostLike 资源,但在您的情况下,这不是必需的。

在您的 Controller 中,您将能够像这样处理您的帖子:
self.posts = Post.query(null, BaseService.errorHandler(self));

self.like = function(post) {
   post.$like(function() {
      angular.forEach(self.posts, function(post, index, obj) {
            if (post.id == id) {
                post.usersVoted.push('voted');
                post.voted=true;
            };
        });
   }, BaseService.errorHandler(self));
};

您可以将 errorHandler 方法添加到 BaseService 以消除一些重复。它看起来像这样:
self.errorHandler = function(viewModel) {
   return function(error) {
      BaseService.accessErrors(error.data);
      viewModel.cerrorMessages = BaseService.cerrorMessages;
   };
};

关于angularjs - 如何正确地将 Controller 和服务从 AngularJS 转换为使用 ng-resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33884463/

相关文章:

javascript - Angular Controller 抛出 $injector 错误

angularjs - 如何获取 AngularStrap 事件选项卡?

javascript - 装饰 Angulars $ExceptionHandler 时如何防止令人讨厌的副作用?

javascript - Angular Js 工具栏问题

javascript - $resource的angularjs无限请求循环

javascript - 使用 $ngresource promise Angularjs 填充选择标签

angularjs - 将内容添加到 Angular 指令中的嵌入内容

javascript - Split 不是函数 : Trying to get response from api through GET using ngResource

angularjs - 通过 angularjs 从 REST api 建模关系数据

javascript - Angular - ngResource 打破了数据绑定(bind)