AngularJS不提供任何直接实现服务继承的机制,但是对于您而言,您可以使用$
provide.decorator扩展
baseService自身或像
ChildService使用普通Javascript
的原型一样使用它。在我的实践中,为了使服务具有可配置的状态和行为,我使用provider。在以下所有示例中,控制台输出将为
World 。
装饰器
如果您
baseService的模块中不需要原件,则可以装饰它
柱塞
function alertService() { this.add = function(level, message) { switch(level) { case 'success': console.log(message); } }}function baseService(alertService) { this.message = "Hello"; this.perform = function () { alertService.add("success",this.message); };}angular. module('app',[]). config(['$provide', function($provide) { $provide.decorator('baseService', function($delegate) { $delegate.message = 'World'; return $delegate; }); }]). service('alertService', alertService). service('baseService', ['alertService',baseService]). controller('ctrl', ['baseService', function(baseService) { baseService.perform(); }]);
原型继承
柱塞
function alertService() { this.add = function(level, message) { switch(level) { case 'success': console.log(message); } }}function baseService(alertService) { this.message = "Hello"; this.perform = function () { alertService.add("success",this.message); };}function ChildService(baseService) { angular.extend(ChildService.prototype, baseService); this.message = "World";}angular. module('app',[]). service('alertService', alertService). service('baseService', ['alertService',baseService]). service('ChildService', ['baseService',ChildService]). controller('ctrl', ['ChildService', function(ChildService) { ChildService.perform(); }]);
提供者
柱塞
function alertService() { this.add = function(level, message) { switch(level) { case 'success': console.log(message); } }}function baseService() { var message = "Hello"; this.setMessage = function(msg) { message = msg; } function Service(alertService) { this.perform = function () { alertService.add("success", message); }; } function Factory(alertService) { return new Service(alertService); } this.$get = ['alertService', Factory];}angular. module('app',[]). provider('baseService', baseService). config(['baseServiceProvider', function(baseServiceProvider) { baseServiceProvider.setMessage('World'); }]). service('alertService', alertService). controller('ctrl', ['baseService', function(baseService) { baseService.perform(); }]);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)