将变量存储在$ rootScope中是一种好习惯吗? [英] Is storing variables in $rootScope good practice?

查看:414
本文介绍了将变量存储在$ rootScope中是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've altered the settings file to just a JS file, added var tempSettings = to the beginning of the file, and added it in index.html. This way it gets loaded with the initial HTML, ensuring it will exist when app.run goes. The settings service then takes this tempSettings variable and puts it in the service. To clean up, I remove the tempSettings pointer.

名为 settings.js

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

已添加到index.html:

Added to 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:我发现了问题

由于设置文件是异步加载的,因此有时会发生模块尝试在加载之前使用设置的情况.我将为您提供最新的解决方案.我已经将设置移到了服务中,那肯定更好.

Update 1: I found a problem

Because the settings file is loaded async, it sometimes happens that a module tries to use the settings before they are loaded. I'll keep you updated on solutions. I have moved the settings into a service, that is definitely better.

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

When I google how to store environment settings in AngularJS apps, I come across options using Grunt or Gulp (and there's probably others as well), but to me this option seems much more obvious. Meaning that there's probably a good reason not to use it. Is this way of storing settings a bad idea?

我的应用程序根目录中有一个名为settings.json的文件,看起来像这样:

I have in my app root a file called settings.json which looks something like this:

{
  "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中有一些内容,如下所示:

I then have a little bit in app.run that looks like this:

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.整个方法确实很简单.这种设计有缺陷吗?

And now whenever I need a setting I can always go to $rootScope.settings.userApiBase or whatever. It makes sense to me, because all I have to do is to make sure settings.json is ignored on check-in. The whole method is really straight forward. Is there a flaw to this design?

推荐答案

尽量不要污染 $ rootScope

Try not to pollute the $rootScope Here as much as possible. Make a Settings service that handles the settings instead. Services are singleton objects so once you initialize the service, the settings will be available everywhere you inject the service.

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 中:

MyApp.run(function (Settings) {
    Settings.initialize();
}

然后,每当您要访问控制器或其他服务或其他内容中的 Settings 时,只需调用 Settings.get()即可返回您的设置.只需确保将 Settings 服务注入使用它的任何设备中即可(就像我在第二个代码块中所做的一样).

Then, whenever you want to access Settings in a controller or another service or something, simply call Settings.get() which will return your settings. Just make sure to inject the Settings service into anything that uses it (like I did in the second code block).

这篇关于将变量存储在$ rootScope中是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆