更新2:我发现了一个解决方案
我已经改变了设置文件只是一个JS文件,添加var tempSettings =
到文件的开头,并在index.html的补充它。这样它就会加载最初的HTML,确保它在app.run运行时会存在。然后设置服务将这个tempSettings
变量放入服务中。为了清理,我删除了tempSettings指针。
新建设置文件名为settings.js
var tempSettings = {
"environment": "development",
[...]
添加到index.html的:
<script src="settings.js"></script>
服务:
myApp.service("settings", function(){
var settings = null;
this.initialize = function() {
settings = tempSettings;
tempSettings = undefined;
};
this.get = function() {
return settings;
}
});
更新1:我发现了一个问题
由于设置文件是异步加载的,因此有时会发生模块尝试在加载之前使用设置。我会及时更新解决方案。我已将设置转移到服务中,这绝对更好。
原来的问题
当我谷歌如何存储在AngularJS应用环境设置,我遇到选项使用咕噜或咕嘟咕嘟(可能还有其他人也),但对我来说这个选项似乎更明显。这意味着可能有一个不使用它的好理由。这种存储设置的方式是一个坏主意吗?
我在我的应用程序的根文件名为settings.json这看起来是这样的:
{
"settingsFile": true,
"environment": "development",
"logLevel": "debug",
"userApiBase": "http://localhost/covlelogin/web/api/",
"oAuth": {
"google":{
"endpoint": "https://accounts.google.com/o/oauth2/auth",
"clientId": "12345",
"scope": "email profile",
"state": "MyToken123",
"redirectUri": "http://localhost/loginadmin/web/oAuthRedirect",
"responseType": "code",
"approvalPrompt": "force"
}
}
}
然后我有一点点app.run,看起来像这样:
MyApp.run(function ($rootScope, $http) {
//Load settings
$http.get('settings.json').
success(function (settings) {
if (settings.settingsFile){
$rootScope.settings = settings;
console.log("Settings loaded");
}else{
console.log("Error loading settings. File may be corrupt.");
//Additional error handling
}
}).
error(function (data) {
console.log("Error getting settings file.");
//Additional error handling
})
});
现在,无论何时我需要设置,我总是可以去$rootScope.settings.userApiBase
或其他任何地方。这对我来说很合理,因为我所要做的就是确保在检入时忽略settings.json。整个方法非常简单。这种设计有缺陷吗?
我没有找到“不污染$ rootScope”的原因。你能提供任何链接阅读吗? –