1

根据Todd Motto's styleguide, Controllers chapter角:依赖注入与原型继承

继承:扩展的控制器类时使用原型继承

我尝试实施它在我的控制器:

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); 

但是,正如你所看到的,我必须始终设置在BaseController中需要用于与服务器端通信的3210。是否有可能将其注入CommunicationService注入TagModalController?然后我的代码看起来就像这样:

function BaseController(CommunicationService){ 
    'use strict'; 

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

和方法this.setRestService(CommunicationService);将不再需要。有没有什么方法可以在AngularJS中为控制器实现Angular DI的原型继承?预先感谢您的每一个答案。

回答

1

这可以被认为是一个必要的罪恶。即使使用ES2015类,父类构造函数have to be specified explicitly with super的参数也是如此。

您可能要借用类使用继承的模式,做

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

将变量传递给BaseController构造,特别是如果有应该有过一个以上的相关性。

BaseController未被$controller实例化,因此不会受益于角度DI,this是将BaseController与子级联系起来的唯一东西。为了使它能够访问TagModalController注入的依赖项,必须将它们分配为this属性,并因此暴露给范围(角度控制器没有考虑到this的设计,并且controllerAs只是用于弥补$scope缺点的语法糖)。这不是一件好事。