本文介绍了设计 AngularJS 服务的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个可以与 REST 服务器交互的 AngularJS 客户端应用程序.

I'm writing an AngularJS client application that would interact with a REST server.

为了管理客户端/服务器交互,我使用了 $resource 抽象.实际上,我将每个资源编写为一个单独的 service 并仅将其注入将要使用它的控制器.

To manage the client / server interaction I'm using the $resource abstraction.Actually I'm writing every resource as a separated service and injecting it only in the controllers that are gonna use it.

我已经开始使用 angularjs-seed 进行开发,所以在我分离的 services.js 文件我有越来越多的服务:

I've started to develop using the angularjs-seed, so in my separed services.js file I've got an increasing number of services:

angular.module('testReqService', ['ngResource']).
    factory('TestReq', function($resource){
    return $resource('http://test-url.com/api/test', {}, {});
});
angular.module('registerService', ['ngResource']).
    factory('Register', function($resource){
    return $resource('http://test-url.com/api/user/new', {}, {});
});
//More services here...

一切正常,但我想知道这是否是最好的方法.

Everything works fine, but I'm wondering if this is the best approach.

因此,最好为不同的 REST 请求编写单独的服务并将它们仅注入需要它的控制器中,或者更好的方法是为每个请求编写具有不同方法和 URL 的单个服务请求?

So, is better to write separate services for different REST requests and inject them only in the controllers that need it, or a better approach is to write a single service with different methods and URL for every request?

推荐答案

我更喜欢第二种方法:

var resources = angular.module("myapp.resources", ['ngResource']);

resources.factory('Constants', [
    function() {
        return {
            RESOURCE_URL: "http://www.example.com/rest"
        }
    }
]);

resources.factory('Rest', ['Constants', '$resource', function(C, $resource) {
    return {
        Users: $resource(C.RESOURCE_URL + '/users/:id', {
            id: '@id',
        }, {})
        , Posts: $resource(C.RESOURCE_URL + '/posts/:user', {
              user: '@'
        }, {})
    }
}]);

当您有多个资源时,管理控制器中的所有依赖项会变得非常烦人.这样,您所要做的就是注入一个.在我看来,阅读控制器时也更容易理解:

When you have several resources, become very annoying to manage all the dependencies in your controller. That way, all you have to do is inject a single one. It is also, in my opinion, easier to understand when reading the controller:

$scope.user = Rest.Users.get({id: 1});

更容易理解

$scope.user = Users.get({id: 1});

这篇关于设计 AngularJS 服务的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 12:34