Extending a base class in an Angular service

后端 未结 2 1759
星月不相逢
星月不相逢 2020-12-31 22:25

I have a base class that I would like to extend in a service to help get data in to the angular scope. I have searched around the net for a solution, but have not found one

2条回答
  •  Happy的楠姐
    2020-12-31 23:05

    I pulled off this trick recently.

    I will start by defining a plain JavaScript constructor. This does not need to be an angular service. What I do is that, later, the extending constructors can pass any necessary injections by parameter. So, this will be the base "class" of my angular services. This is where I would expose anything I want all angular services to inherit.

    function ParentService($http) {
       this.$http = $http;
    }
    
    ParentService.prototype.foo = function () {
        alert("Hello World");
    };
    

    Then I will proceed to define a child constructor using prototypal inheritance. This constructor will indeed be an angular service (you can tell by my use of $inject at the end).

    function ChildService($http) {
        Parent.call(this, $http);
    }
    
    ChildService.prototype = new ParentService();
    ChildService.prototype.baz = function() {
       return this.$http.get('/sample/rest/call');
    }
    ChildService.$inject = ['$http'];
    

    Then I will proceed to register the services à la carte in the corresponding angular modules:

    var app = angular.module('SampleApp', []);
    app.service('child', ChildService);
    

    Finally, in my controller I will simply inject my service, which will be an instance of my ChildService constructor, which in turn extends my ParentService constructor:

    app.controller('MainCtrl', ['$scope', 'child', function ($scope, child) {
        child.foo(); //alert("Hello World")
        var promise = child.bar();
    }]);
    

    You can see a JSFiddle here

    Also there is an interesting video in Youtube from ngConf called Writing A Massive Angular App which covers some of these topics and a few other ideas on code reusability with angular.

提交回复
热议问题