How to inherit from base provider (not the provider factory)?

自古美人都是妖i 提交于 2019-12-12 03:00:24

问题


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:


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);
      }
    }
  };
}]);


来源:https://stackoverflow.com/questions/30921294/how-to-inherit-from-base-provider-not-the-provider-factory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!