我有下一个服务:
angular.module('app').service('BaseService', function (alertService) { var service = {}; service.message = "Hello"; service.perform = function () { alertService.add("success",service.message); }; return service; });
现在,我想在某些“ ChildService”中继承此服务,并在“ World!”上覆盖消息。我希望调用ChildService.perform()将显示“ World!”警报。
什么是正确的方法?
AngularJS不提供任何直接实现服务继承的机制,但是对于您而言,您可以使用$ provide.decorator扩展BaseService自身或像ChildService使用普通JavaScript 的原型一样使用它。在我的实践中,为了使服务具有可配置的状态和行为,我使用provider。在以下所有示例中,控制台输出将为 World 。
BaseService
ChildService
装饰器
如果您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(); }]);