在TypeScript中为AngularJS常量使用静态字符串

时间:2015-08-18 20:49:16

标签: typescript

我想通过使用静态数据来引用常量的名称,但由于执行顺序,它无法解决。该怎么做呢。

module tasks {

    export class TasksController {

        //name of the controller used for referencing or defining this controller
        public static named: string = 'tasksController';
        public static templateUrl: string = 'apps/demo/tasks/tasks.tpl.html';

        //dependencies to other services etc., referenced in the constructor
        static $inject: string[] = ['tasksConfig'/*TasksConfiguration.named*/];

        //constructor getting injected dependency instances
        constructor(appConfig: ApplicationConfiguration) {
        }

    }


    angular
        .module('Tasks', [])
        .controller(TasksController.named, TasksController);
}


module tasks {

    export class TasksConfiguration {

        //id of the configuration used for referencing or defining
        public static named = 'tasksConfig';

        public static values: ApplicationConfiguration = {
            appId: 'demo.tasks',
            appName: 'App_Name_Tasks',
            appCategory: 5,
            rootUrl: '/tasks'
        };
    }

    angular.module('Demo')
        .constant(TasksConfiguration.named, TasksConfiguration.values);
}

当我使用TaskConfiguration.named而不是'taskConfig'时,$ inject不起作用,因为它没有初始化,当解释器到达该行时。但我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

  

但由于执行顺序

,它无效

一般来说,这是您遇到out时遇到的风险。

在您的情况下,您可以重新排序类:

module tasks {

    export class TasksConfiguration {

        //id of the configuration used for referencing or defining
        public static named = 'tasksConfig';

        public static values: ApplicationConfiguration = {
            appId: 'demo.tasks',
            appName: 'App_Name_Tasks',
            appCategory: 5,
            rootUrl: '/tasks'
        };
    }

    angular.module('Demo')
        .constant(TasksConfiguration.named, TasksConfiguration.values);
}

module tasks {

    export class TasksController {

        //name of the controller used for referencing or defining this controller
        public static named: string = 'tasksController';
        public static templateUrl: string = 'apps/demo/tasks/tasks.tpl.html';

        //dependencies to other services etc., referenced in the constructor
        static $inject: string[] = ['tasksConfig'/*TasksConfiguration.named*/];

        //constructor getting injected dependency instances
        constructor(appConfig: ApplicationConfiguration) {
        }

    }


    angular
        .module('Tasks', [])
        .controller(TasksController.named, TasksController);
}

甚至更好转移到外部模块

  

实际上,这两个文件放在不同的角度模块中。也许有另一种注入依赖关系的方法?

确实使用外部模块并避开--out。更多:https://github.com/TypeStrong/atom-typescript/blob/master/docs/out.md