我有一个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);
但是,在myMethod
(var resource = new MyResource()
)的第一行执行失败:
ReferenceError: MyResource is undefined
at MyController.myMethod (myModule.module.js:214)
...
使用的技术:
如何将ngInject应用于ECMA6类方法?
答案 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();
}
}