【问题标题】:How to $inject into Angular class w/ES6如何使用 ES6 注入 Angular 类
【发布时间】:2015-10-16 03:25:48
【问题描述】:

使用带有 ES6/7 和 Babel 的 Angular 1.4,我可以在类块之后使用以下代码成功地将参数注入到名为 Controller 的类中:

class Controller {
    constructor($scope, $state, $window) {...}
    ...
}
Controller.$inject = ["$scope", "$state", "$window"]

但是,在构造函数的正上方看到注入参数会更清晰。我见过其他人使用静态 $inject,但我得到一个错误。这是我正在尝试的:

class Controller {
    static $inject = ["$scope", "$state", "$window"]
    constructor($scope, $state, $window) {...}
    ...
}

为什么会导致这个错误?它似乎对其他人有用。

Unexpected token (2:11)
  1 | class Controller {
  2 |     static $inject = ["$scope", "$state", "$window"]
    |  
              ^

【问题讨论】:

    标签: angularjs dependency-injection ecmascript-6


    【解决方案1】:

    这是一个实验性的建议语法。在 Babel 中,您必须启用 es7.classProperties。通过

    optional: ['es7.classProperties']
    

    到巴别塔。确切的方法取决于您的转译方式。

    如果你想做标准的 ES6,你也可以做

    static get $inject(){ return ["$scope", "$state", "$window"]; }
    

    【讨论】:

    • 谢谢。这就是我所缺少的。我在 gulp 中添加了以下内容,现在它可以工作了。 .transform(babelify.configure({ optional: ["es7.classProperties"] }))
    【解决方案2】:

    另一种方法是使用$injector.annotate(fn),Angular 使用它来进行依赖注入,它允许您获取传递给它的函数的参数。您可以利用它来获取所有constructor() 参数的名称,并使用$injector.get() 检索它们。

    这是另一个线程中的link to answer,以及带有演示的直接link to a fiddle

    【讨论】:

      猜你喜欢
      • 2016-04-20
      • 2019-06-27
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      相关资源
      最近更新 更多