简体   繁体   中英

Access Rails env variable from Angular Controller

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'] %>";
    }
  }
});

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?

Thanks in advance

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

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 %>;
});

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM