Brent Hronik
Brent Hronik

Reputation: 2427

AngularJS support multiple environments

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'?

Upvotes: 1

Views: 1876

Answers (1)

WeNeigh
WeNeigh

Reputation: 3509

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

Upvotes: 4

Related Questions