我正在尝试使用 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);
最佳答案
ES6 模块与 Angular 1.x 的模块系统不兼容。这意味着 export
ing 和 import
ing 服务和 Controller 将无法工作,您需要使用 Angular 的模块系统注册和注入(inject)它们。
randomTVNames.service.js:
import mainModule from '../../mainModule';
class RandomTVNames {
// ... snip ...
}
RandomTVNames.$inject = [ /* ... snip ... */ ];
mainModule.service('randomTVNames', RandomTVNames);
home.controller.js:
import mainModule from '../../mainModule';
class HomeController {
constructor($scope, randomTVNames) {
this.$scope = $scope;
this.tv = randomTVNames;
}
}
HomeController.$inject = ['$scope', 'randomTVNames'];
mainModule.controller('HomeController', HomeController);
然后在你的主 webpack 文件中,确保导入它们,以便它们被捆绑:
import 'services/randomTVNames.service';
import 'controllers/controller.service';
关于javascript - 使用 ES6 和 webpack 导入 Angular 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33982984/