AngularJS 读取配置文件的更好方法?
AngularJS better way to read config file?
我构建了一个需要动态配置的 angularJS 应用程序,因此我创建了一个包含所需配置的 config.json 文件,并决定加载app.config 中的配置文件如下:
angular.module("myapp",[]).config([ my injections] , function(my providers){
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET","config.json"); //my config file
xhr.send();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
//config file parsed, set up params
}
}
})
我这样做的原因是因为 $http 没有注入配置状态,我不想 "configure" 在控制器级别的应用程序。
应用程序运行良好。它做了我想做的事,一切都很好......除了单元测试(使用业力 + 茉莉花)。
即使在 karma.conf 我有:
{pattern: 'config.json',served:true,watched:false,included:false}
已定义,当我启动 karma 时,我收到一个关于 config.json 404 的 cli [WARN]。我的单元测试以查看是否配置了所有内容,但失败了(即它没有读取 config.json)
有没有更好的方法来编写单元测试的配置文件?
在我们的应用程序中,我们有外部文件 config.js,它只包含提供配置常量的普通模块。
angular.module('myAppPrefixconfig')
.constant('PLAIN_CONSTANT', 'value'),
.constant('APP_CONFIG', {...});
在您的应用程序中,您依赖它,并且有普通的 http 请求 - 可以通过适当的配置由您的后端解决。
在 Karma 测试中,您可以直接在 karma.conf 中提供 'testing config'。
我构建了一个需要动态配置的 angularJS 应用程序,因此我创建了一个包含所需配置的 config.json 文件,并决定加载app.config 中的配置文件如下:
angular.module("myapp",[]).config([ my injections] , function(my providers){
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET","config.json"); //my config file
xhr.send();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
//config file parsed, set up params
}
}
})
我这样做的原因是因为 $http 没有注入配置状态,我不想 "configure" 在控制器级别的应用程序。
应用程序运行良好。它做了我想做的事,一切都很好......除了单元测试(使用业力 + 茉莉花)。
即使在 karma.conf 我有:
{pattern: 'config.json',served:true,watched:false,included:false}
已定义,当我启动 karma 时,我收到一个关于 config.json 404 的 cli [WARN]。我的单元测试以查看是否配置了所有内容,但失败了(即它没有读取 config.json)
有没有更好的方法来编写单元测试的配置文件?
在我们的应用程序中,我们有外部文件 config.js,它只包含提供配置常量的普通模块。
angular.module('myAppPrefixconfig')
.constant('PLAIN_CONSTANT', 'value'),
.constant('APP_CONFIG', {...});
在您的应用程序中,您依赖它,并且有普通的 http 请求 - 可以通过适当的配置由您的后端解决。
在 Karma 测试中,您可以直接在 karma.conf 中提供 'testing config'。