Angular: Dependency Injection with prototypal inheritance

雨燕双飞 提交于 2019-12-11 10:44:01

问题


According to Todd Motto's styleguide, Controllers chapter:

Inheritance: Use prototypal inheritance when extending controller classes

I try to implement it in my controllers:

function BaseController(){
    'use strict';

    this._path = '';
    this._restService = undefined;
}

/**
 * Boring JSDocs
 */
BaseController.prototype.getById = function(id) {
    return this._restService.getById(this._path, id);
};

TagModalController.prototype = Object.create(BaseController.prototype);

/**
 * Even more boring JSDocs
 */
function TagModalController(CommunicationService, $modalInstance, mode, 
    id, CommandService) {
    'use strict';

    // boring assertions

    this.setPath('tags');
    this.setRestService(CommunicationService);

But, as you can see, I have to always set restService which is needed in BaseController for communication with server side. Is any possibility to inject it like CommunicationService is injected into TagModalController? Then my code will look like this:

function BaseController(CommunicationService){
    'use strict';

    this._path = '';
    this._restService = CommunicationService;
}

And method this.setRestService(CommunicationService); won't be needed anymore. Is there any way to achieve Angular DI with prototypal inheritance for controllers in AngularJS? Thank you in advance for every answer.


回答1:


This can be considered a necessary evil. Even with ES2015 classes the arguments for parent class constructor have to be specified explicitly with super.

You may want to borrow the pattern that classes use for inheritance and do

angular.bind(this, BaseController)(CommunicationService, ...);

to pass variables to BaseController constructor, especially if there is more than one dependency that should be passed there.

BaseController isn't instantiated by $controller and thus doesn't benefit from Angular DI, this is the only thing that associates BaseController with children. In order to give it an access to TagModalController injected dependencies, they have to be assigned as this properties and thus exposed to scope (Angular controllers weren't designed with this in mind, and controllerAs is just syntactic sugar to remedy $scope drawbacks). Which is not a very good thing.



来源:https://stackoverflow.com/questions/33064219/angular-dependency-injection-with-prototypal-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!