设计 AngularJS 服务的更好方法

编程入门 行业动态 更新时间:2024-10-28 07:31:39
本文介绍了设计 AngularJS 服务的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在编写一个可以与 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/api/test', {}, {});
});
angular.module('registerService', ['ngResource']).
    factory('Register', function($resource){
    return $resource('http://test-url/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/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 服务的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

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

发布评论

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

>www.elefans.com

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