从角度控制器访问Rails env变量

时间:2022-01-29 23:34:36

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

我有一个模块叫EnvConfigurationService,js.erb:

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

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

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

目的是提供对来自不同角度和常规js类的“MY_SECRET_KEY”的访问。如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?

不过,返回的字符串始终为空。有什么问题吗?

Thanks in advance

谢谢提前

1 个解决方案

#1


3  

This website shows 4 great ways to pass info from Rails to Angular

这个网站展示了将信息从Rails传递到angle的4种方法

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.

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

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

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.

在我看来,如果你想解决这个问题,还有另外一种方法。我将在rails中创建一条路径,在响应中向您返回env变量。

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.

然后,每当服务需要首次提供env变量时,您可以使用$http.get()和缓存:true选项,该选项在服务调用中添加,以从路由/控制器获取数据,并且只需要获取一次。

#1


3  

This website shows 4 great ways to pass info from Rails to Angular

这个网站展示了将信息从Rails传递到angle的4种方法

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.

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

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

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.

在我看来,如果你想解决这个问题,还有另外一种方法。我将在rails中创建一条路径,在响应中向您返回env变量。

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.

然后,每当服务需要首次提供env变量时,您可以使用$http.get()和缓存:true选项,该选项在服务调用中添加,以从路由/控制器获取数据,并且只需要获取一次。