如何从基础提供者(而不是提供者工厂)继承?
How to inherit from base provider (not the provider factory)?
假设我有这个基础提供商:
angular.module('app').provider('BaseClient', function () {
this.setSomething = function (something) {
// Store `something` somewhere
return this;
};
});
现在还有另外 2 个子提供商:
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');
});
如何使 ClientA
和 ClientB
继承 BaseClient
的提供程序部分,以便我可以调用 clientAProvider.setSomething('aaa')
和 clientBProvider.setSomething('bbb')
以及存储每个提供商的值,同时使用相同的 setSomething
实现?
我有一堆这样的提供者(不止这两个),其中提供者部分始终相同,配置实现始终相同,但这些提供者的工厂部分不同。
想法?
您可以将 BaseClientProvider
注入您的 ClientA
提供商。
完整代码在这里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);
}
}
};
}]);
假设我有这个基础提供商:
angular.module('app').provider('BaseClient', function () {
this.setSomething = function (something) {
// Store `something` somewhere
return this;
};
});
现在还有另外 2 个子提供商:
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');
});
如何使 ClientA
和 ClientB
继承 BaseClient
的提供程序部分,以便我可以调用 clientAProvider.setSomething('aaa')
和 clientBProvider.setSomething('bbb')
以及存储每个提供商的值,同时使用相同的 setSomething
实现?
我有一堆这样的提供者(不止这两个),其中提供者部分始终相同,配置实现始终相同,但这些提供者的工厂部分不同。
想法?
您可以将 BaseClientProvider
注入您的 ClientA
提供商。
完整代码在这里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);
}
}
};
}]);