从角控制器访问的Rails环境变量 [英] Access Rails env variable from Angular Controller

查看:185
本文介绍了从角控制器访问的Rails环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我叫EnvConfigurationService下面的模块,js.erb:

I have the following module called EnvConfigurationService,js.erb:

#../angular/services/config/EnvConfigurationService,js.erb

angular.module('mgApp.services').factory('EnvConfigurationService', function () {
return {
    getMySecretKey: function () {
        return "<%= ENV['MY_SECRET_KEY'] %>";
    }
  }
});

我们的目的是从不同的角度和普通的js类提供给MY_SECRET_KEY访问。像userController.js以下内容:

The intention is to provide access to 'MY_SECRET_KEY' from different angular and regular js classes. Like the following on userController.js:

angular.module('mgApp.controllers').controller('userController', ['$scope', '$http', 'EnvConfigurationService', function($scope, $http, EnvConfigurationService) {
  var uri = EnvConfigurationService.getMySecretKey();
  ...
}]);

不过,返回的字符串总是空的。任何想法可能是错误/失踪了?

Still, the returned string is always empty. Any ideas what might be wrong/missing?

在此先感谢

推荐答案

本网站显示4伟大的方式来传递从Rails的角度来信息

选项3号指出,如果你要使用插值那样,你可能需要调用 .html_safe 像本例中所示。

Option number 3 states that if you are going to use interpolation like that, you may need to call .html_safe like shown in this example.

itemsApp.service('itemsAppInitializer', function(){
  return <%= @item.to_json.html_safe %>;
});

在我看来,有可能是,如果你想,你可以解决这个问题的另一种方式。我想创建一个轨道路线返回ENV变量你的反应。

In my opinion, there could be one other way that you could tackle this issue if you wanted to. I would create a route in rails that returns env variables to you in the response.

然后,每当服务需要首次提供ENV变量,可以使用 $ http.get()缓存:真在服务调用添加选项可以获取从路由/控制器的数据,只需要一次读取它。

Then whenever the service needs to provide env variables for the first time, you can use $http.get() with the cache: true option added in your service call to fetch that data from the route/controller, and only need to fetch it once.

这篇关于从角控制器访问的Rails环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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