javascript - 使用 ES6 和 webpack 导入 Angular 服务

标签 javascript angularjs ecmascript-6 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 的模块系统不兼容。这意味着 exporting 和 importing 服务和 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/

相关文章:

javascript - 检测ul列表中的类,如果没有找到则删除li :first-child

javascript - Extjs 布局扩展导致 ext-all.js 中出现错误

javascript - 在 Angular 中检查 sessionStorage 并将变量传递给 $scope 的正确方法是什么?

javascript - form.$error.required 和 form.$invalid 的冲突验证

ecmascript-6 - 使用 Browserify/Babel 在 ES6 Express 中渲染 React 组件不起作用

javascript - 类型错误 : divOutput is null

ecmascript-6 - ES6 模板字符串作为变量?

javascript - D3 力向图 : update node position

javascript - 使用 javascript 从浏览器打印 XML 或 TXT 文件

angularjs - Angular : How to get $routeProvider after app. 配置