angularjs - Angular : Have multiple functions in one Service

标签 angularjs service

是否可以在一项服务中具有多种功能?

我的图书服务中有这个:

(function() {
    'use strict';
    angular
            .module('app.core')
            .service('BookService', BookService);

        BookService.$inject = ['$resource'];
        /* @ngInject */
        function BookService($resource) {
            return $resource('/api/book/:id', {
                id: '@id'
            }, {
                'get': {
                    method: 'GET',
                    cache: true
                },
              'query': {
                method: 'GET',
                isArray: true,
                cache: true
            },
            });
        }
})()

但在同一个服务中,我想要另一个函数,我将传递其他参数,例如:
 return $resource('/api/book/:name', {
                name: '@name'
            }, {
                'get': {
                    method: 'GET',
                    cache: true
                },
               'query': {
                method: 'GET',
                isArray: true,
                cache: true
            },
            });

我的 Controller 看起来像这样并且有两个不同的调用:
BookService.get({
                id: 2
            }, function(book) {})

BookService.get({
                name: "bookTitle"
            }, function(book) {})

最佳答案

是的你可以。只需定义服务中的功能。最后,返回一个对象,其中包含您要向服务的使用者公开的所有函数。编辑:这适用于工厂。有关服务,请参阅 nathan 的回答。

(function() {
    'use strict';
    angular
        .module('app.core')
        .factory('BookService', BookService);

        BookService.$inject = ['$resource'];
        /* @ngInject */
        function BookService($resource) {
            var getById = function(id){
                return $resource('/api/book/:id', {
                    id: id
                }, {
                    'get': {
                        method: 'GET',
                        cache: true
                    }
                });
            };

            var getByName = function(name) {
                return $resource('/api/book/:name', {
                    name: name
                }, {
                    'get': {
                        method: 'GET',
                        cache: true
                    }
                });
            };

            return {
                getById: getById,
                getByName: getByName
            };

        }
})()

关于angularjs - Angular : Have multiple functions in one Service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36655564/

相关文章:

javascript - AngularJS Material md-list heightt 在 chrome 中完全不同

javascript - 似乎无法访问 json 数据的特定元素

javascript - angularjs:使用来自两个 http 请求的变量

c# - "An error occurred creating the configuration section handler for"-

angularjs - 如何在 bootstrap 3.0/bootstrap-ui 的 Accordion 标题中添加按钮?

javascript - Kendo AutoComplete + AngularJS + 对象数组

java - 服务已经在运行,但它不应该在使用后台服务代码的位置

java - 运行服务时 Activity 卡住

vb.net - 使用以SYSTEM身份运行的vb.net应用程序,如何为每个登录用户启动分离的进程?

安卓服务完全停止