1

What is the conventional way to support multiple environments(develop, staging, production, ci) in an AngularJS application?

For a more concrete example, how would one go about provisioning(probably requires an additional tool) a server endpoint in a config somewhere and then read that server endpoint in for use elsewhere, such as calls like $http.get(server_endpoint+'/rest/api/route'?

1 Answer 1

4

You can define an Angular constant, inject it into the required service/controller and refer to environment-specific values

angular.module('YourApp')
.constant('AppConstants', {
   'SERVER_ENDPOINT': 'http://api.example.com',
   'SHOW_DEBUG': true
});

You would use that like

$http.get(AppConstants.SERVER_ENDPOINT + '/rest/api/route')

If you use Grunt or Gulp, there's a nice task that allows you to create an Angular constant file based on the environment.

grunt-ng-constant

gulp-ng-constant

Grunt example:

ngconstant: {
            options: {
                name: 'config',
            },
            dev: {
                options: {
                    dest: '<%= yeoman.app %>/scripts/config.js'
                },
                constants: {
                    ENV: {
                        FB_APP_ID: '123456'
                    }
                }
            },
            prod: {
                options: {
                    dest: '<%= yeoman.dist %>/scripts/config.js'
                },
                constants: {
                    ENV: {
                        FB_APP_ID: '98765'
                    }
                }
            }
        }

The tasks that create the production and development version of the app call ngconstant:prod and ngconstant:dev respectively

Sign up to request clarification or add additional context in comments.

2 Comments

is there any particular file where the angular.module('YourApp')... block should be located?
It doesn't matter where you define the constant, but it is standard practice to put it in its own file, say appconstants.js, similar to putting each controller/service/filter/directive in a separate file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.