[英]importing angular services with ES6 and webpack
我正在嘗試使用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
和import
服務及控制器將無法正常工作,您需要使用Angular的模塊系統進行注冊和注入。
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';
沒有擺脫$ inject的方法,除非您沒有縮小代碼(但我希望您是)。
Angular正在使用變量的名稱注入變量,因此,當它看到$ scope時,便知道要查找並注入它,但是在最小化代碼時,變量名稱便被更改($ scope變為c等),而angular不知道哪個對象你想注入。
那是$ inject的目的,因為沒有縮小字符串。
請看看這個裝載機 。 它有助於您嘗試做的事情。 但是請注意在您的js文件中的任意位置添加“ ngInject”,這會注入任何內容
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.