AngularJS service inheritance

后端 未结 4 653
北海茫月
北海茫月 2020-12-28 09:14

I have next service:

angular.module(\'app\').service(\'BaseService\', function (alertService) {
   var service = {};
   service.message =  \"Hello\";
   serv         


        
4条回答
  •  -上瘾入骨i
    2020-12-28 09:47

    Module A with service ASvc:

    (function(angular) {
      var app = angular.module('A', []);
    
      app.service('ASvc', ['$http', function($http) {
         var ASvc = {
           list: function() {
             return $http({
               method: 'GET',
               url: '/A'
             });
           },
    
           getInstructions: function(id) {
             return $http({
               method: 'GET',
               url: '/instructions/' + id
             });
           }
         };
         return ASvc;
      }]);
    })(angular);
    

    Module B with service BSvc which inherits from ASvc:

    (function(angular) {
      var app = angular.module('B', ['A']);
    
      app.service('BSvc', ['$http', 'ASvc', function($http, ASvc) {
         var BSvc = {
           list: function() {
             return $http({
               method: 'GET',
               url: '/B'
             });
           }
         };
    
         BSvc.__proto__ = ASvc; // here you're settting the inheritance
         return BSvc;
      }]);
    })(angular);
    

    Now, when you call BSvc.getInstructions(30775);, you're calling the parent's service (ASvc) getInstructions function from BSvc, and when you call BSvc.list(), you're calling a method which was overridden from ASvc in BSvc. Inheritance.

    And BTW, when I'm passing angular as argument to the closure, instead of referring to the global angular variable directly from within it, I'm allowing code minifiers and obfuscators to do things like this:

    (function(j){var c=j.module('A',[]);})(angular); // and so on
    

    It's a good thing to have in mind and I consider it being a good practice ;)

提交回复
热议问题