Angular:在一项服务中具有多种功能 [英] Angular : Have multiple functions in one Service

查看:60
本文介绍了Angular:在一项服务中具有多种功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to have multiple functions in one service ?

我的图书服务中有此内容:

I have this in my book 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
            },
            });
        }
})()

但是在同一服务中,我想拥有另一个函数,在该函数中我将传递其他参数,例如:

But in the same service i want to have another function where i will pass other parameters, ex :

 return $resource('/api/book/:name', {
                name: '@name'
            }, {
                'get': {
                    method: 'GET',
                    cache: true
                },
               'query': {
                method: 'GET',
                isArray: true,
                cache: true
            },
            });

我的控制器看起来像这样,有两个不同的调用:

My controller looks like this and has two differents calls:

BookService.get({
                id: 2
            }, function(book) {})

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

推荐答案

可以.只需在服务中定义功能即可.最后,返回一个对象,其中包含要向服务使用者公开的所有功能.这适用于工厂.有关服务,请参阅内森的答案.

Yes you can. Just define the functions within the service. At the end, return an object that contains all the functions you want to expose to the consumers of the service. this works for factories. For services, see nathan's answer.

(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
            };

        }
})()

这篇关于Angular:在一项服务中具有多种功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆