问题描述
在ZF2中工作时,我们使用的配置文件可能因开发人员而异,并且在生产和暂存环境之间可能有所不同.它非常方便,因此我想将其复制到Angular 2.
When working in ZF2 we use configuration files that may vary from developer to developer and between production and staging environments. Its pretty convenient and as such I want to replicate this for Angular 2.
它在ZF2中的工作方式:我们有一个config文件夹,其配置名为:settings.local.php和settings.global.php.然后,我们使用gitignore文件忽略其中包含local的任何内容.
How it works in ZF2: We have a config folder with configs named: settings.local.php and settings.global.php. We then use a gitignore file to ignore anything with local in it.
我想对Angular 2做类似的事情,但不确定100%做到这一点的最佳方法.
I would like to do something similar with Angular 2 and am not 100% sure of the best method to go about this.
对于Angular 2,我当时想拥有一个config文件夹,然后使用一项服务来获取配置文件...
For Angular 2 I was thinking of having a config folder and then using a service to grab the configuration files...
Angular 2中是否有类似这样的约定?
Is there a convention for something like this in Angular 2?
推荐答案
我也来自ZF2背景,并且想要这种功能.我不能保证这是实现这一目标的公约",但是它对我和我的处境都非常适用.
I also come from a ZF2 background and wanted this sort of functionality. I can't promise that this is the 'convention' for achieving this however it works perfectly for me and my situation.
简而言之,我结合使用JSON配置文件和 grunt-ng-constant (需要 Grunt obvs...)
In short I use a combination of JSON config files and grunt-ng-constant (requires Grunt obvs..)
我的Gruntfile.js
中的我的ngconstant
配置看起来像这样:
My ngconstant
config in my Gruntfile.js
looks like this:
ngconstant: {
options: {
constants: {
config: grunt.file.readJSON('config/config.global.json')
},
name: 'constants',
dest: 'public/js/src/config.js',
wrap: '/* global angular */\n\n(function ()\n{\n\t\'use strict\';\n\t\n\t{%= __ngModule %}\n\t\n})();\n'
},
dev: {
constants: {
config: grunt.file.readJSON('config/config.dev.json')
}
},
live: {
constants: {
config: grunt.file.readJSON('config/config.live.json')
}
}
}
所有文件的位置都由您决定..但是从理论上讲,config.global.json
是所有默认配置的存放位置.然后,根据运行ngconstant:live
还是ngconstant:dev
,它将把相应的配置与global合并并覆盖所有重叠.
The location of all your files is up to you.. but the theory of this is that config.global.json
is where all your default configs go. Then depending on whether you run ngconstant:live
or ngconstant:dev
it will merge the corresponding config with global and overwrite any overlaps.
这会将配置保存到新的Angular constant
public/js/src/config.js
中,然后我可以将其注入到我想要的任何服务/控制器中.
This saves the config to a new Angular constant
, public/js/src/config.js
, which I can then inject into any service / controller that I want.
/**
* My Controller
*/
angular
.module('ctrls')
.controller('myCtrl', myCtrl);
/**
* @param $scope
* @param config
*/
function myCtrl($scope, config)
{
$scope.someConfig = config.someConfigValue;
}
这篇关于Angular 2-如何使用配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!