Angular:具有原型继承的依赖注入 [英] Angular: Dependency Injection with prototypal inheritance
问题描述
继承:扩展控制器类时使用原型继承
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);
但是,正如您所看到的,我必须始终设置restService
,这是与服务器端通信所需的BaseController
.是否有可能像将CommunicationService
注入到TagModalController
中一样注入它?然后我的代码将如下所示:
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;
}
并且不再需要方法this.setRestService(CommunicationService);
.有没有办法通过AngularJS中的控制器原型继承来实现Angular DI?预先感谢您的每一个回答.
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.
推荐答案
可以认为这是必要的邪恶.即使使用ES2015类,父类构造函数的参数也必须是用super
明确指定.
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, ...);
将变量传递给BaseController
构造函数,尤其是当存在多个依赖关系时.
to pass variables to BaseController
constructor, especially if there is more than one dependency that should be passed there.
BaseController不会由$controller
实例化,因此无法从Angular DI中受益,this
是将BaseController与子级关联的唯一内容.为了使其能够访问TagModalController注入的依赖项,必须将它们分配为this
属性,并因此暴露给作用域(角度控制器的设计并未考虑this
,controllerAs只是用于纠正$scope
缺点).这不是一件好事.
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.
这篇关于Angular:具有原型继承的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!