Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

javascript - how can i extend a service

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.

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:

    factory('ExtendedService', function($http){
        var ExtendedService = BasicService();
        ExtendedService['method_four'] = function(){/* code for method four */}
        return ExtendedService;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

More cleaner and imperative way

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...