I am trying to create a set of Controller classes which are derived from a base class that have many dependencies. Every time I want to create a derived class I have to copy the base class constructor dependencies into the derived class constructor. This seems particularly ugly and repetitive. See below;
module MyModule
{
export class ParentCtrl
{
constructor($http, $provide, $scope,$compile,MyService,$parse,$timeout)
{
console.log('parent');
}
FunctionA(){...}
...
FunctionZ(){...}
}
export class ChildCtrl extends ParentCtrl
{
constructor($http, $provide, $scope,$compile,MyService,$parse,$timeout)
{
super($http, $provide, $scope,$compile,MyService,$parse,$timeout);
console.log('child');
}
FunctionA(){ console.log('Override A'); }
}
export class GrandChildCtrl extends ChildCtrl
{
constructor($http, $provide, $scope,$compile,MyService,$parse,$timeout)
{
super($http, $provide, $scope,$compile,MyService,$parse,$timeout);
console.log('grandchild');
}
FunctionB(){ console.log('Override B'); }
}
}
I have removed the type definitions from the constructor parameters for ease of reading.
Is there a way to avoid these lengthy constructor being duplicated? I had thought of having a function in the base/Parent controller which is called from the constructor to inject the required types. This would mean dependencies would be confined to the base class.
Has anyone successfully tried this before?
Angular is not friendly to controller inheritance. It favors composition. Consider factoring out the utility code into an Angular Service : https://docs.angularjs.org/guide/services (which are singletons) or just another typescript utility class.
If you must you could just inject the $injector
in the base : https://docs.angularjs.org/api/auto/service/$injector and use that to load what you need inside the base constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With