小编dev*_*n81的帖子

Angularjs Typescript控制器继承和依赖注入

我正在尝试创建一组Controller类,这些类派生自具有许多依赖项的基类.每次我想创建派生类时,我都必须将基类构造函数依赖项复制到派生类构造函数中.这看起来特别难看和重复.见下文;

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'); }
     }
 }
Run Code Online (Sandbox Code Playgroud)

我已从构造函数参数中删除了类型定义,以便于阅读.

有没有办法避免这些冗长的构造函数被复制?我曾想过在base/Parent控制器中有一个函数,它从构造函数中调用以注入所需的类型.这意味着依赖关系将局限于基类.

有没有人成功尝试过这个?

javascript inheritance angularjs typescript angularjs-controller

7
推荐指数
1
解决办法
5619
查看次数