AngularJS服务继承

AngularJS服务继承,第1张

AngularJS服务继承

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5126474.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存