AngularJS support multiple environments

。_饼干妹妹 提交于 2019-12-11 19:24:19

问题


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:


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



来源:https://stackoverflow.com/questions/31881017/angularjs-support-multiple-environments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!