简体   繁体   中英

AngularJS controller inheritance in ES6

I've got project in AngularJS and I have baseController and child controller inheriting from it.

class BaseController {
    constructor($log, $state) {
        'ngInject';

        this.$log = $log;
        this.$state = $state;
    }
}

class ChildController extends BaseController {

    constructor(myService) {
        'ngInject';

        super();
        this.myService = myService;
    }
}

My question is: Do I need to inject all parent dependency injections into child controller even when I am not using it?

Above example shows what I want to achieve, but it's not working. Anyone got idea if I can achieve it without passing BaseController services into super($scope, $state) invocation?

The $injector Service only injects dependencies into the constructor function of the instantiated class. It does not inject into construction functions of ancestor classes.

To construct a controller with injectables from an ancestor class, use the $injector service and angular.extend :

class BaseController {
    constructor($log, $window) {
        'ngInject';

        this.$log = $log;
        this.$window = $window;
    }
}

class ChildController  ̶e̶x̶t̶e̶n̶d̶s̶ ̶B̶a̶s̶e̶C̶o̶n̶t̶r̶o̶l̶l̶e̶r̶ {

    constructor(myService, $injector) {
        'ngInject';
        var base = $injector.instantiate(BaseController);
        angular.extend(this, base);
        ̶s̶u̶p̶e̶r̶(̶)̶;̶
        this.myService = myService;
    }
    $onInit() {
      this.$log.info("$onInit");
      this.$log.log(this.base);
    }
}

The DEMO

 class BaseController { constructor($log, $window) { 'ngInject'; this.$log = $log; this.$window = $window; this.base = "Hello from BaseController"; } } class ChildController { constructor(myService, $injector) { 'ngInject'; var base = $injector.instantiate(BaseController); angular.extend(this, base); //super(); this.myService = myService; } $onInit() { this.$log.info("$onInit"); this.$log.log(this.base); } } angular.module("app",[]) .controller("child", ChildController) .value("myService", {}) 
 <script src="//unpkg.com/angular/angular.js"></script> <body ng-app="app" ng-controller="child as vm"> {{vm.base}} </body> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM