How to inherit from base provider (not the provide

2019-09-13 17:26发布

Say I have this base provider:

angular.module('app').provider('BaseClient', function () {
    this.setSomething = function (something) {
        // Store `something` somewhere
        return this;
    };
});

And now these 2 other sub-providers:

angular.module('app').provider('ClientA', function () {
    this.$get = function () {
        return {
            foo: function () {
                console.log('FOO', /* Read `something`, needs to output 'aaa' */);
            }
        }
    };
});

angular.module('app').provider('ClientB', function () {
    this.$get = function () {
        return {
            bar: function () {
                console.log('BAR', /* Read `something`, needs to output 'bbb' */);
            }
        }
    };
});

angular.module('app').config(function (clientAProvider, clientBProvider) {
    clientAProvider.setSomething('aaa');
    clientBProvider.setSomething('bbb');
});

How do I make ClientA and ClientB inherit the provider section of BaseClient in such a way that I can call clientAProvider.setSomething('aaa') and clientBProvider.setSomething('bbb') and store that value per provider, while using the same setSomething implementation?

I have a bunch of these providers (more than these 2) where the provider section is always the same, the configuration implementation is always the same but the factory section of those providers are different.

Thoughts?

1条回答
姐就是有狂的资本
2楼-- · 2019-09-13 18:09

You could inject BaseClientProvider into your ClientA provider.

Full code is here plnkr


app.provider('BaseClient', function() {
  this.config = {
    something: null
  };

  this.setSomething = function(something) {
    this.config.something = something;
    return this;
  };

  this.$get = function() {};
});

app.provider('ClientA', ['BaseClientProvider', function(BaseClientProvider) {
  var self = this;
  angular.extend(self, BaseClientProvider);
  self.$get = function() {
    return {
      foo: function() {
        console.log('FOO', self.config.something);
      }
    }
  };
}]);
查看更多
登录 后发表回答