简体   繁体   English

为AngularJS项目组织API服务

[英]Organize API service for AngularJS project

Our project has about 50 API endpoints. 我们的项目有大约50个API端点。 Our api follows the Rest style. 我们的api遵循Rest风格。 For example, we have image api with 4 methods: GET, POST, DELETE and PUT. 例如,我们有4种方法的图像API:GET,POST,DELETE和PUT。

Currently, I create 1 service for each endpoint. 目前,我为每个端点创建1个服务。 Each service contains the method to call API. 每个服务都包含调用API的方法。 We don't have any unit test yet. 我们还没有任何单元测试。 Here is an example of our service: 这是我们服务的一个例子:

export default function userApi(apiHelper, $http, $q) {
    let self = this;
    self.getUserData = getUserData;
    self.getPhoneCodes = getPhoneCodes;
    self.updateUser = updateUser;
    // Implementation below
}

Other service just follow that style. 其他服务只是遵循这种风格。 But now I am afraid that this approach will create too many services. 但是,现在恐怕这种方法会产生太多的服务。

My teammate suggests that we should call $http service directly in the controller. 我的队友建议我们应该直接在控制器中调用$ http服务。

Do you think this way is better? 您认为这样更好吗? Thanks in advance. 提前致谢。

This is totally not a good idea to use $http inside your controller. 在控制器中使用$http绝对不是一个好主意。 Especially in your case when there is a lot of different API calls. 尤其是在您有很多不同的API调用的情况下。

If you are using multiple services containing the linked API call like UserService, ProductService,... you will have all the calls stored in one file. 如果您正在使用包含链接的API调用的多个服务(例如UserService, ProductService,...则所有调用都存储在一个文件中。

You can then call them anywhere in the code easily. 然后,您可以轻松地在代码中的任何位置调用它们。 If one day you need to change an API call because the back-end changed, you will have to change it at one place (in the service file) and not in every controller where you use it 如果有一天由于后端发生更改而需要更改API调用,则必须在一个位置(服务文件中)而不是在使用它的每个控制器中都更改它

Ideally it is not a good idea to use $http in controllers. 理想情况下,在控制器中使用$http不是一个好主意。 Any business logic should be implemented in factories / services . 任何业务逻辑都应在factories / services实施。

Below is my implementation that I have been using it for a while in my projects. 下面是我在项目中使用了一段时间的实现。

factory for making service calls to RESTFul API 用于对RESTFul API进行服务调用的工厂

(function () {
    angular.module('myApp').factory('serviceFactory', function ($http) {
        var obj = {};
        var serviceUrl = "HOST URL/";
        // common service call
        obj.serviceCall = function (URL, method, reqParam) {
            var reqObject = {
                url: serviceUrl + URL,
                method: method || 'GET',
                data: reqParam,
                headers: {
                    'Content-Type': 'application/json'
                }
            };
            return $http(reqObject)
                .then(function success(success) {
                    return response.data;
                }, function err(error) {
                    alert("There was an error occured. Please try again after some time.");
                    return false;
                });
        }
        return obj;
    });
})();

Usage in Controller 控制器中的用法

serviceFactory
    .serviceCall(CONSTANTS.URL, 'GET', reqParams)
    .then(function(data) {
        // data is available
    });

Totally agree with Weedoze that you should not put $http in your controller. 完全同意Weedoze的意见,您不应在控制器中放入$ http。 So 50 endpoints, with 1-4 verbs each is a lot of server side functions. 所以50个端点(每个端点带有1-4个动词)是许多服务器端功能。 Practically speaking, it is unlikely you are going to want to moderate that many functions directly from a controller either. 实际上,您不太可能希望直接从控制器中调整许多功能。 And you are right, that would be a ton of angular services if you made a service for each endpoint. 没错,如果为每个端点提供服务,那将是大量的角度服务。

Consider grouping the related functions in a service that can contain coordinating functions as well. 考虑将服务中的相关功能分组,也可以包含协调功能。 For example your user service could manage (and I'm making some fake endpoints): 例如,您的用户服务可以管理(并且我正在制作一些虚假的端点):

User Endpoint, Login Information Endpoint 用户端点,登录信息端点

And it may contain a function that logs a user in and returns the profile of that user (for example). 并且它可能包含一个功能,用于登录用户并返回该用户的配置文件(例如)。

First of all, there's no such thing as "Too much services". 首先,没有“服务太多”之类的东西。

The best thing you can do is keep away your business logic, and your API calls from your controllers. 您能做的最好的事情就是远离您的业务逻辑以及您的控制器发出的API调用。

If you start using the $http service in your controller you are gonna end up repeating yourself throughout your hole application. 如果您开始在控制器中使用$ http服务,那么最终将在整个Hole应用程序中重复一次。

One thing I could add, though, is that if you are following a REST approach in your webservices, you could make good use of angular-resource ( Link ). 不过,我要补充的一件事是,如果您在Web服务中遵循REST方法,则可以充分利用angular-resourceLink )。

This library allows you to create services that come with the most common actions for a resource service (save POST , delete DELETE , query GET collection, get GET single object) and it's super extensible as well. 该库使您可以创建资源服务最常用操作附带的服务(保存POST ,删除DELETE ,查询GET集合,获取GET单个对象),并且它也具有超级可扩展性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM