Environment Variables in AngularJS and Ionic

By in
88
Environment Variables in AngularJS and Ionic

I was reading my friend Josh Bavari’s blog post on Managing Environment Variables for your Ionic Application where he describes his method for managing variables that change between environments (like connection strings and API endpoints). This got me thinking about how I have solved this problem in the past. Since Ionic makes use of Angular you get to apply all of your favorite Angular tips and tricks when you build an Ionic app. The method I’m going to describe can be used in any Angular app.

I like to create an Angular module that will hold these values and expose them as constants. I realize that calling something that is variable in nature a constant is weird but it refers to the way the variables will be exposed to my Angular application. Let’s have a look:

First I’ll create a module for my constants:

https://gist.github.com/jeff-french/c6b6a48bacc7e32a6044

Don’t worry about that @@apiUrl, I’ll explain that in just a sec.

Next I’ll add my constants as a dependency on my main module:

https://gist.github.com/jeff-french/497b09d6fb4dfce6efd1

So now my API url can be injected into any services or controllers that need to make use of it like this:

https://gist.github.com/jeff-french/050898e45cb80d7b8fc4

Cool! So we’re gonna make requests to @@apiUrl? Nope! That is a variable substitution syntax used by a couple of Grunt and Gulp plugins, grunt-replace and gulp-replace-task, respectively. Before we can replace that @@apiUrl with the right value for a given environment we need to put the right values in some configuration files:

- config/ 
 ` localdev.json 
 ` test.json 
 ` production.json

Each file will have contents similar to:

https://gist.github.com/jeff-french/27f583a2a871aefac0a0

Great! Now we can use a Gulp or Grunt task to stuff the contents of the appropriate file into the constant in our module. I’ll use Gulp here but you can use Grunt if you prefer:

https://gist.github.com/jeff-french/688a40761c09b8a35616

Now I can call my Gulp task like so:

gulp replace --env production

So now my Gulp (or Grunt) task reads in the settings from the file that matches the environment name, replaces the values into the constants file, and then the constants are injected into any services or controllers that need them.

I really like using the Angular constants approach because it prevents my variable values from being assigned to “magic” global variables that my app depends on being defined. In this way they are injected where ever they are needed which will make the code very readable and testable in the same manner as all the rest of my Angular code.


Originally published at geekindulgence.com.

Leave a reply

Your email address will not be published. Required fields are marked *