带有babel和ng-annotate / ngInject的ECMA6基于类的控制器导致ReferenceError

时间:2016-06-06 21:54:34

标签: angularjs ecmascript-6 webpack babeljs ng-annotate

我有一个Angular 1.4控制器,其方法依赖于资源服务。我用ng-annotate注释了该类的构造函数,但仍然,Angular诅咒在该方法中找不到该服务:

var MyResourceFactory = require("myResource.service");

class MyController {
    // @ngInject
    constructor($location, $stateParams, $state, MyResource) {
        ... // some initialization code
    }

    myMethod(data) {
        var resource = new MyResource();
        resource.data = data;
        resource.save();
    }
}

module.exports = angular.module("MyModule", [])
    .factory('MyResource', MyResourceFactory)
    .controller('MyController', MyController)
    .config(routes);

但是,在myMethodvar resource = new MyResource())的第一行执行失败:

ReferenceError: MyResource is undefined
    at MyController.myMethod (myModule.module.js:214)
    ...

使用的技术:

  • Angular 1.4
  • 的WebPack
  • 巴别
  • NG-注释

如何将ngInject应用于ECMA6类方法?

1 个答案:

答案 0 :(得分:2)

MyResource是构造函数方法的局部变量,它在外部不可用。在这种情况下的惯常做法是将其作为公共财产:

class MyController {
    // @ngInject
    constructor($location, $stateParams, $state, MyResource) {
        this.MyResource = MyResource;
        // ... some initialization code
    }

    myMethod(data) {
        var resource = new this.MyResource();
        resource.data = data;
        resource.save();
    }
}