Javascript 角度:带有原型继承的依赖注入

Javascript 角度:带有原型继承的依赖注入,javascript,angularjs,dependency-injection,angularjs-controller,prototypal-inheritance,Javascript,Angularjs,Dependency Injection,Angularjs Controller,Prototypal Inheritance,根据: 继承:在扩展控制器类时使用原型继承 我尝试在我的控制器中实现它: function BaseController(){ 'use strict'; this._path = ''; this._restService = undefined; } /** * Boring JSDocs */ BaseController.prototype.getById = function(id) { return this._restService.getB

根据:

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

我尝试在我的控制器中实现它:

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);
但是,正如您所看到的,我必须始终设置
restService
,这是
BaseController
中与服务器端通信所需的。是否有可能像将
CommunicationService
注入
TagModalController
一样注入它?然后我的代码将如下所示:

function BaseController(CommunicationService){
    'use strict';

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

方法
this.setRestService(通信服务)将不再需要。有没有办法通过AngularJS中控制器的原型继承实现AngularDI?提前感谢您的每一个回答。

这可以被认为是一种必要的邪恶。即使使用ES2015类,父类构造函数的参数也是如此

您可能希望借用类用于继承的模式并执行以下操作:

angular.bind(this, BaseController)(CommunicationService, ...);
将变量传递给
BaseController
构造函数,尤其是当有多个依赖项应传递到该构造函数时

BaseController不是由
$controller
实例化的,因此不会从Angular DI中受益,
这是唯一将BaseController与子级关联的东西。为了让它能够访问TagModalController注入的依赖项,必须将它们分配为
this
属性,从而暴露于作用域(角度控制器的设计没有考虑到
this
,controllerAs只是弥补
$scope
缺点的语法糖)。这不是一件好事