常规的angularjs语法到es6语法以便迁移

时间:2018-07-25 18:53:53

标签: javascript angularjs ecmascript-6

如何在es6中将静态属性设置为 class

这是我的问题: 我有一个名为 Commands 的工厂。

commandsFactory.js

angular.module('mainModule')
.factory('Commands', [function () {
return{
// a lot of commands here
}

该工厂在另一个名为 Module 的工厂中用作依赖项:

moduleFactory.js

.factory('K_Module', ['Commands', function (Commands) {
// here I'm using Commands anytime and anywhere I need
// also all the instance created by this factory had access to Commands

}

重构后,我有以下内容:

commandFactory.js

function CommandsFactory() {
return all my commands
}
export {
    CommandsFactory
}

我添加了一个新文件,以便导出一个名为

的模块

data.module.js

import $parser from '../parsers/parsers.module';
import $communication from '../communication/communication.module';
import {Connectors, CommandsFactory} from './Commands'

export default require('angular')
    .module('core.data', [$parser, $communication])
    .factory("Connectors", Connectors)
    .factory("Commands", CommandsFactory)
    .name;

我正在另一个名为

的模块中调用该模块

kModule

import $data from '../core/data/data.module';
import {K_Module, K_Matrix} from './ModuleFactory'
export default require('angular')
    .module('kModules', [$data])
    .service('K_Module', K_Module)
    .name;

新的K_Module看起来像这样(这是问题所在):

class K_Module {
    constructor(data, Commands, DataProxy, $q) {// I don't want to include these dependencies (except data) each time I create a K_Module
        'ngInject';
        let _self = this;
        _self.Commands = Commands;
        _self.DataProxy = DataProxy;
        _self.$q = $q;
//... other stuff

是否可以将Commands,$ q和DataProxy设置为静态属性? 所以我可以继承这些属性,而不必每次都写? var

1 个答案:

答案 0 :(得分:0)

我的问题是我每个依赖项的冗余。

好吧,解决方案就是将它们设为当前模块的全局变量。

let _Commands;
let _DataProxy;
let _$q;
class K_Module {
        constructor(data, Commands, DataProxy, $q) {// I don't want to include these dependencies (except data) each time I create a K_Module
            'ngInject';
            let _self = this;
            _Commands = Commands;
            _DataProxy = DataProxy;
            _$q = $q;
    //... other stuff

这样,该模块中的每个实例都可以访问该变量