热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何扩展服务-howcaniextendaservice

Iamfairlynewtoangularjsandamnotabletofindanydocumentationorexamplesforthis.WhatI

I am fairly new to angularjs and am not able to find any documentation or examples for this. What I am looking to do is to extend a basic service so that i can use the methods defined under the basic service from other services. So for example say i have a basic service as follows.

对于angularjs来说,我是一个新手,我找不到任何相关的文档或例子。我要做的是扩展一个基本的服务,这样我就可以使用其他服务在基本服务下定义的方法。比如我有一个基本的服务,如下所示。

angular.module('myServices', []).

    factory('BasicService', function($http){
        var some_arg = 'abcd'
        var BasicService = {
            method_one: function(arg=some_arg){ /*code for method one*/},
            method_two: function(arg=some_arg){ /*code for method two*/},
            method_three: function(arg=some_arg){ /*code for method three*/},
        });
        return BasicService;
    }   
);

Now i want to define an Extended service that extends from the above BasicService so that i can use methods defined under the BasicService from my extended service. Maybe something like:

现在,我想定义一个扩展的服务,它从上面的BasicService扩展,这样我就可以使用从我的扩展服务中定义的BasicService定义的方法。也许类似:

    factory('ExtendedService', function($http){
        var ExtendedService = BasicService();
        ExtendedService['method_four'] = function(){/* code for method four */}
        return ExtendedService;
    }

6 个解决方案

#1


21  

Your ExtendedServiceshould inject the BasicServicein order to be able to access it. Beside that BasicService is an object literal, so you can't actually call it as function (BasicService()).

您的ExtendedServiceshould注入BasicServicein以便能够访问它。在BasicService的旁边是一个对象文字,因此您不能实际地将它调用为function (BasicService())。

.factory('ExtendedService', function($http, BasicService){
  BasicService['method_four'] = function(){};
  return BasicService;
}

#2


68  

More cleaner and imperative way

更干净、更迫切的方式

.factory('ExtendedService', function($http, BasicService){

    var extended = angular.extend(BasicService, {})
    extended.method = function() {
        // ...
    }
    return extended;
}

#3


16  

In my opinion, a better way:

在我看来,更好的办法是:

.factory('ExtendedService', function($http, BasicService){
    var service = angular.copy(BasicService);

    service.methodFour = function(){
        //code for method four
    };

    return service;
});

Here at least does not change the inherited service.

这里至少不会更改继承的服务。

#4


3  

Sorry if I post here but may be it's a good place to do it. I refer to this post

对不起,如果我在这里张贴,但可能是一个好地方。我指的是这篇文章

watch out to extend a service/factory because are singleton so you can extend a service/factory once.

注意扩展服务/工厂,因为是单例的,所以可以只扩展一次服务/工厂。

'use strict';
            angular.module('animal', [])
                .factory('Animal',function(){
                        return {
                            vocalization:'',
                            vocalize : function () {
                                console.log('vocalize: ' + this.vocalization);
                            }
                        }

                });
                angular.module('dog', ['animal'])
                    .factory('Dog', function (Animal) {
                        Animal.vocalization = 'bark bark!';
                        Animal.color = 'red';
                        return Animal;
                    });

                angular.module('cat', ['animal'])
                   .factory('Cat', function (Animal) {
                        Animal.vocalization = 'meowwww';
                        Animal.color = 'white';
                        return Animal;
                    });
                 angular.module('app', ['dog','cat'])
                .controller('MainCtrl',function($scope,Cat,Dog){
                     $scope.cat = Cat;
                     $scope.dog = Dog;
                     console.log($scope.cat);
                     console.log($scope.dog);
                    //$scope.cat = Cat;
                });

but if you do like

但如果你喜欢的话

'use strict';
            angular.module('animal', [])
                .factory('Animal',function(){
                    return function(vocalization){
                        return {
                            vocalization:vocalization,
                            vocalize : function () {
                                console.log('vocalize: ' + this.vocalization);
                            }
                        }
                    }
                });    
                angular.module('app', ['animal'])
                    .factory('Dog', function (Animal) {
                        function ngDog(){
                            this.prop = 'my prop 1';
                            this.myMethod = function(){
                                console.log('test 1');
                            }
                        }
                        return angular.extend(Animal('bark bark!'), new ngDog());
                    })
                    .factory('Cat', function (Animal) {
                        function ngCat(){
                            this.prop = 'my prop 2';
                            this.myMethod = function(){
                                console.log('test 2');
                            }
                        }
                        return angular.extend(Animal('meooow'), new ngCat());
                    })
                .controller('MainCtrl',function($scope,Cat,Dog){
                     $scope.cat = Cat;
                     $scope.dog = Dog;
                     console.log($scope.cat);
                     console.log($scope.dog);
                    //$scope.cat = Cat;
                });

it works

它的工作原理

#5


1  

I wrote an $extend provider that uses Backbone's extend under the hood -- So you get both prototype and static property extending in case you need them -- Plus you get parent/child constructors -- see gist @ https://gist.github.com/asafebgi/5fabc708356ea4271f51

我编写了一个$extend提供程序,它使用了主干的扩展——如果需要的话,您可以获得原型和静态属性扩展——以及父/子构造函数——请参见gist @ https://gist.github.com/asafebgi/5fabc708356ea4271f51

#6


-1  

To expand on Stewie's answer, you could also do the following:

要扩展Stewie的答案,你也可以做以下事情:

.factory('ExtendedService', function($http, BasicService){
    var service = {
        method_one: BasicService.method_one,
        method_two: BasicService.method_two,
        method_three: BasicService.method_three,
        method_four: method_four
    });

    return service ;

    function method_four(){

    }
}

This has the benefit that the original service is not altered, while keeping it's functionality. You can also choose to use your own implementations in the ExtendedService for the other 3 methods from BasicService.

这样做的好处是,原始服务不会被更改,同时保留它的功能。您还可以为BasicService的其他3个方法在ExtendedService中使用自己的实现。


推荐阅读
  • 使用nodejs爬取b站番剧数据,计算最佳追番推荐
    本文介绍了如何使用nodejs爬取b站番剧数据,并通过计算得出最佳追番推荐。通过调用相关接口获取番剧数据和评分数据,以及使用相应的算法进行计算。该方法可以帮助用户找到适合自己的番剧进行观看。 ... [详细]
  • 本文介绍了闭包的定义和运转机制,重点解释了闭包如何能够接触外部函数的作用域中的变量。通过词法作用域的查找规则,闭包可以访问外部函数的作用域。同时还提到了闭包的作用和影响。 ... [详细]
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 本文详细介绍了解决全栈跨域问题的方法及步骤,包括添加权限、设置Access-Control-Allow-Origin、白名单等。通过这些操作,可以实现在不同服务器上的数据访问,并解决后台报错问题。同时,还提供了解决second页面访问数据的方法。 ... [详细]
  • 本文总结了Java中日期格式化的常用方法,并给出了示例代码。通过使用SimpleDateFormat类和jstl fmt标签库,可以实现日期的格式化和显示。在页面中添加相应的标签库引用后,可以使用不同的日期格式化样式来显示当前年份和月份。该文提供了详细的代码示例和说明。 ... [详细]
  • 本文介绍了使用AJAX的POST请求实现数据修改功能的方法。通过ajax-post技术,可以实现在输入某个id后,通过ajax技术调用post.jsp修改具有该id记录的姓名的值。文章还提到了AJAX的概念和作用,以及使用async参数和open()方法的注意事项。同时强调了不推荐使用async=false的情况,并解释了JavaScript等待服务器响应的机制。 ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 本文介绍了如何在给定的有序字符序列中插入新字符,并保持序列的有序性。通过示例代码演示了插入过程,以及插入后的字符序列。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • Voicewo在线语音识别转换jQuery插件的特点和示例
    本文介绍了一款名为Voicewo的在线语音识别转换jQuery插件,该插件具有快速、架构、风格、扩展和兼容等特点,适合在互联网应用中使用。同时还提供了一个快速示例供开发人员参考。 ... [详细]
author-avatar
暖暖de苹果的马甲
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有