我是 Angular 新手,我正在尝试使用 ES6。
我的依赖注入有问题,我无法让它工作。
我的index.js:
import './index-state.css!';
import angular from 'angular';
import 'angular-ui-router';
import IndexStateController from './index-state-controller';
import indexRouteConfig from './index-route';
const dependencies = [
'ui.router'
];
export default angular
.module('index-state-component', dependencies)
.controller('IndexStateController', IndexStateController)
.config(indexRouteConfig);
我的 index-state.controller.js 是:
class IndexStateController {
constructor($timeout) {
this.$timeout = $timeout;
this.controllerName = 'Example Controller';
console.log(this.$timeout);
}
}
IndexStateController.$inject =['$timeout'];
export default [
IndexStateController
];
我在 console.log(this.$timeout) 上收到“未定义”。
有人可以帮我解决这个问题吗?
Thanks
我认为你的问题是你正在导出一个包含控制器的数组,而不是导出控制器类本身,这意味着你已经覆盖了$inject
具有空依赖集的属性:
export default [
IndexStateController
];
应该:
export default IndexStateController;
或者,您可以在导出中包含注入值:
export default [
'$timeout',
IndexStateController
];
另一种解决方案,如果你使用类似的东西gulp
构建代码就是用 babel 之类的东西编译 es6,然后使用ngAnnotate
自动进行注射。在这种情况下,您需要将该类标记为需要注入:
class IndexStateController {
constructor($timeout) {
"ngInject"
this.$timeout = $timeout;
this.controllerName = 'Example Controller';
console.log(this.$timeout);
}
}
export default IndexStateController;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)