How to access local ENV variables in angular js

Is it possible to access ENV variables from angular?

I have an angular 1.2.8 application compiled through Brunch.io

It is hosted as the main node application for the hero. (I compile locally, then click)

I read a few things about replacing tokens at compile time for ENV variables.

However, I would rather be able to push the code to several different servers and allow the correct local settings using only ENV variables.

Thanks!

+6
source share
2 answers

You cannot get ENV variables in a browser. You can send a request for the recreation service to your server and get env on the backend, and then return to the client

Quick example: (Express.js)

app.get("/rest/getenv", function(req, res) { var env = process.env.ENV_VARIABLE; res.json({result: env}); }); 

Edit:

You need to protect this remainder url along with the token as strings. Or anyone can reach this URL and get the value of an environment variable. This could be a security issue.

+10
source

There are several ways to do this, and as mentioned above, you can just make an API call, however, this creates an unnecessary delay in your application. I would recommend inserting env variables into your angular support team on your server. It probably sounds a little confusing, but it's easier than it sounds.

I wrote a blog post comparing the different ways to enter env varialbes into angular and explaining why you should use this approach: https://medium.com/@kudresov/a-better-way-to-inject-environmental-variables-in -angular-d3b2d01a3c5e

I also created an example Node angular project to show how it works: https://github.com/kudresov/angular-config-vars

+8
source

All Articles