[英]Angular 1.5 & ES6 -Dependency injection
我是棱角分明的新手,我正在嘗試使用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上得到'undefined'(這個。$ timeout)。
有人可以幫我解決這個問題嗎?
謝謝
我認為您的問題是您正在導出包含控制器的數組而不是導出控制器類本身,這意味着您已使用一組空的依賴項覆蓋$inject
屬性:
export default [
IndexStateController
];
應該:
export default IndexStateController;
或者,您可以在導出中包含注入值:
export default [
'$timeout',
IndexStateController
];
如果你使用像另一種解決方案gulp
,以建立自己的代碼編譯器ES6的東西,如巴別塔,然后用ngAnnotate
自動執行注射。 在這種情況下,您可能希望將類標記為需要注入:
class IndexStateController {
constructor($timeout) {
"ngInject"
this.$timeout = $timeout;
this.controllerName = 'Example Controller';
console.log(this.$timeout);
}
}
export default IndexStateController;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.