【问题标题】:Angular.js DI with (ES6) classes and inheritance带有(ES6)类和继承的Angular.js DI
【发布时间】:2015-05-14 18:57:21
【问题描述】:

背景,我们应用程序中类/模块的当前实现是 common.js 和 CoffeeScript 类。我正在拼命寻找与 ES6 或 TypeScript 一起使用的解决方案,但问题仍然存在。

如何使用 Angular-1.x 进行类继承的 DI?

给定代码:

// SuperService.js
class SuperService {
  constructor($http, $q, $etc) {
    // Implementation is not important ...  
  }   
}
export { SubService }

// SubService.js
import { SuperService } from './SuperService';
class SubService extends SuperService {
  constructor($more, $di, $things, $here) {
    // Implementation is not important ... 
    // // // // // // // // // // 
    // Problem exists here ... //
    // // // // // // // // // //
    super($we, $need, $all, $the, $super, \
          $class, $di, $things, $every, $time, $we, \
          $inherit, $from, $it)
  }
}
export { SubService }

必须的,在SubService这里重新定义所有父DI要求才能成功调用super()

我们目前正在做类似于以下的事情:

// CoffeeScript                              // Javascript
app.factory "subService", (Service) ->       app.factory("subService", function(Service) {
  SubService = () ->                           var SubService;
    Service.call(@)                            SubService = function() {
    @                                            Service.call(this);
                                                 return this;
  # Overwrite some stuff on the "Service"      };
  Service::basepath = "/environments"          Service.prototype.basepath = "/environments";
  Service::model = Environment                 Service.prototype.model = Environment;
                                               return new SubService();
  new SubService()                           });

除了丑陋之外,这也不太理想。

【问题讨论】:

  • 您找到解决方案了吗?我们也在以类似的方式接近它,但必须有更好的方法。
  • 正是因为这个原因,我的团队还没有为我们的 Angular 东西切换到 ES6,我们希望这将在 ng-2.0 中的 typescript move 中以某种方式得到解决,但是我们'还没有看到任何解决这个问题的方法。
  • 与大多数其他地方一样,在 AngularJS 中,我认为使用组合而不是继承更容易且更具可读性。

标签: javascript angularjs dependency-injection ecmascript-6


【解决方案1】:

在 SubService.js 的最底部添加这个

SubService.$inject = ['$http', '$q', '$etc', '$more', '$di', '$things', '$here'];

【讨论】:

    【解决方案2】:

    它不是 ES6(它是 ES7),但它可能会让你的船浮起来

    我会通过MikeRyan52 调查angular-decorators

    他组装了一个 @inject 装饰器,其工作原理如下:

    @inject('$http', '$rootScope')
    class SomeClass {
      constructor($http, $rootScope) {
    
      }
    }
    
    @inject('$q')
    class SubClass extends SomeClass {
      constructor($q, ...parentDependencies) { /** parent dependencies caught with a rest parameter **/
        super(...parentDependencies);
      }
    }
    

    the implementation of @inject

    【讨论】:

    • 太好了,感谢您的提示,我认为当您开始将 angular2 功能反向移植回 angular 功能时,最好花时间进行升级 :) 但仍然很高兴看到概念验证,并有选择的余地。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 2018-09-14
    • 1970-01-01
    • 2016-06-24
    相关资源
    最近更新 更多