【发布时间】:2015-11-29 12:53:30
【问题描述】:
我正在尝试使用 ES6 和 webpack 导入 $timeout,但我不断发现 $timeout 未定义。 任何人都可以帮忙吗? 如果有一种不涉及使用 $inject 的方法,我会更喜欢它,因为我正逐渐尝试在我的代码中摆脱 angularjs。
randomTVNames.service.js:
import angular from 'angular';
class RandomTVNames {
constructor($timeout) {
this.tv = ['Shield', 'Walking Dead', 'Castle', 'Leftovers'];
this.timeout = $timeout;
console.log(this.timeout);
}
getName() {
const totalNames = this.tv.length;
const rand = Math.floor(Math.random() * totalNames);
return this.tv[rand];
}
getTimeout(){
this.timeout(function () {
alert("this is timeout")}, 3000);
}
}
RandomTVNames.$inject = ['$timeout'];
//todo - try to inject angular argument (such as $timeout) with $inject
var randomTVNames = new RandomTVNames();
export default randomTVNames;
home.controller.js:
import randomTVNames from '../../services/randomTVNames.service';
import mainModule from '../../mainModule';
class HomeController {
constructor() {
this.tv = randomTVNames;
this.name = 'World';
}
randomTVName($timeout) {
this.name = this.tv.getName();
}
getCtrlTimeout(){
this.tv.getTimeout();
}
}
mainModule.controller('HomeController', HomeController);
【问题讨论】:
-
你在缩小你的代码吗?
-
$timeout不会注入自己。当你在没有任何参数的情况下调用RandomTVNames的构造函数时,你期望什么? -
你的意思是这样的:“var randomTVNames = new RandomTVNames($timeout);”?因为我仍然知道 $timeout 是未定义的
标签: javascript angularjs ecmascript-6 webpack