AngularJS service inheritance

后端 未结 4 652
北海茫月
北海茫月 2020-12-28 09:14

I have next service:

angular.module(\'app\').service(\'BaseService\', function (alertService) {
   var service = {};
   service.message =  \"Hello\";
   serv         


        
4条回答
  •  北海茫月
    2020-12-28 09:28

    Here is an example, based on Constructor/new inheritance(which I would generally recommend against).

    BaseService.$inject = ['alertService']
    function BaseService(alertService) {
        this.message = 'hello'
        this.alertService = alertService
    }
    
    BaseService.prototype.perform = function perform() {
        this.alertService.add("success",this.message);
    }
    
    
    ChildService.$inject = ['alertService']
    function ChildService(alertService) {
        this.message = 'hello world'
        this.alertService = alertService
    }
    
    ChildService.prototype = Object.create(BaseService.prototype)
    

    And then you would just include these as services:

    angular.module('app')
        .service('BaseService', BaseService)
        .service('ChildService', ChildService)
    

提交回复
热议问题