Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了angularjs – 将变量存储在$rootScope的良好实践中?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
更新2:我找到了解决方

我已将设置文件更改为JS文件,将var tempSetTings =添加文件的开头,并将其添加到index.html中.这样它就会加载初始HTML,确保它在app.run运行时就会存在.然后,设置服务获取此tempSetTings变量并将其放入服务中.要清理,我删除tempSetTings指针.

新设置文件名为setTings.js

var tempSetTings = {
  "environment": "development",[...]

添加到index.html:

<script src="setTings.js"></script>

服务:

@H_9_5@myApp.service("setTings",function(){ var setTings = null; this.initialize = function() { setTings = tempSetTings; tempSetTings = undefined; }; this.get = function() { return setTings; } });

更新1:我发现了一个问题

由于设置文件是异步加载的,因此有时会发生模块在加载之前尝试使用这些设置.我会告诉你最新的解决方案.我已将设置移动到服务中,这肯定更好.

原始问题

当我谷歌如何在AngularJS应用程序中存储环境设置时,我遇到了使用Grunt或Gulp的选项(并且可能还有其他选项),但对我来说这个选项似乎更加明显.这意味着可能有充分的理由不使用它.这种存储设置的方式是个坏主意吗?

我在我的应用程序根目录中有一个名为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中有一点看起来像这样

@H_9_5@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 Here.创建一个处理设置的设置服务.服务是单例对象,因此一旦初始化服务,设置将在您注入服务的任何位置都可用. @H_9_5@myApp.service("SetTings",function($http) { var setTings = null; this.initialize = function() { $http.get('setTings.json').success(function (s) { if (s.setTingsFilE){ setTings = s; 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 }) }; this.get = function() { return setTings; } return this; });

在MyApp.run中:

@H_9_5@myApp.run(function (SetTings) { SetTings.initialize(); }

然后,只要您想要访问控制器或其他服务中的设置或其他@L_675_21@,只需调用SetTings.get()即可返回您的设置.只需确保将SetTings服务注入任何使用它的东西(就像我在第二个代码块中所做的那样).

大佬总结

以上是大佬教程为你收集整理的angularjs – 将变量存储在$rootScope的良好实践中?全部内容,希望文章能够帮你解决angularjs – 将变量存储在$rootScope的良好实践中?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。