如何动态地设置AngularjJS基本URL以获取环境变量? [英] How to set AngularjJS base URL dynamically based on fetched environment variable?

查看:1353
本文介绍了如何动态地设置AngularjJS基本URL以获取环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个开发和生产环境,使我的URL的不同:

生产:

www.exmaple.com/page

开发:

dev.environment /项目/页

我知道我可以在AngularJS设置基本网址

<基地的HREF =/项目/'/>

但这并不能帮助我在这里。之前,我打开我的AngularJS应用程序,我获取一个配置文件(在app.js,与 .RUN 语句,其内容具有环境变量:

 ])。运行([
  $ rootScope',
  $ HTTP,
  功能 (
    $ rootScope,
    $ HTTP
  ){
    变种configDeferred = $ q.defer();

    //获取配置和设置API
    $ http.get('config.json'),然后(函数(响应){
      $ rootScope.config = response.data;
      configDeferred.resolve();
    });

    //等待加载的配置,然后进入状态
    $ rootScope。$在('$ stateChangeStart',函数(事件,接下来,电流){
      。事件preventDefault();
      $ q.all([configDeferred.promise])。然后(函数(){
        $ state.transitionTo(next.name);
        返回;
      });
    });
 

有没有办法动态设置基本URL的基础上,AngularJS一个获取配置文件(也许用的.htaccess)?

尝试1: 尝试通过 .RUN 来获得配置,并通过NG-HREF设置基本网址:

编辑code以下行我app.js:

  //获取配置和设置API
$ http.get('config.json'),然后(函数(响应){
  $ rootScope.config = response.data;
  $ rootScope.baseUrl = response.data.baseUrl; // '/项目/'
  configDeferred.resolve();
});
 

在我的index.html:

 <基础NG-HREF ={{的baseUrl}}/>
 

看起来这是行不通的:当我改变标签NG-HREF的href属性,它正确加载的内容,但改变了我的网址为 dev.environment /页 dev.environment /项目/页>

更新: 配置文件:

  {
  模式:发展,
  的baseUrl:/项目/
}
 

解决方案

我personnaly做这种东西与咕噜

当我跑我的角度,应用程序我有多个任务:

 >咕噜运行--target =开发
>咕噜运行--target = PROD
>咕噜构建--target =开发
>咕噜构建--target = PROD
>等等...
 

然后咕噜做字符串替换成 grunt- preprocess 模块的帮助:

我的 constants.tpl.js 文件被解析:

  [...]
的baseUrl:/ * @echo ENV_WS_URL * /',
[...]
 

和URL是稀少。

有无限的可能性(字符串替换,文件拷贝等)。

与繁重的做这确保dev的配置文件不进去的生产为例。

我可以把更多的细节,如果你有兴趣,但我只是想告诉你一个不同的方法。

编辑gruntFile例如:

 使用严格的;

module.exports =功能(咕噜){

    / **
     *检索当前目标
     * /
    VAR的目标= grunt.option('目标')|| 开发;
    VAR availableTargets = [
        '开发',
        督促
    ]。

    / **
     *负荷的环境,特定的变量
     * /
    VAR envConfig = grunt.file.readJSON('触摸屏的配置'+目标+'.json');

    / **
     *这是配置对象咕噜用来给每个插件的
     *指示。
     * /
    grunt.initConfig({
        ENV:envConfig,

        / ********* /
        / *建立文件到一个特定的包膜或模式* /
        / ********* /
        preprocess:{
            选项​​:{
                背景:{
                    ENV_WS_URL:'<%= env.wsUrl%>
                }
            },
            常量:{
                SRC:constants.tpl.js,
                DEST:constants.js
            }
        },

        因果报应:{
            单元: {
                CONFIGFILE:'<%= src.karma%>',
                autoWatch:假的,
                singleRun:真
            },
            看: {
                CONFIGFILE:'<%= src.karma%>',
                autoWatch:真正的,
                singleRun:假的
            }
        }

    });


    / **************** /
    / *插件加载* /
    / **************** /
    grunt.loadNpmTasks('grunt- preprocess');

    / ******************* /
    / *可用的任务* /
    / ******************* /
    grunt.registerTask('跑','运行任务,启动Web服务器开发的一部分',['$ P​​ $ pprocess:常量']);

};
 

现在,命令:

 >咕噜运行--target =开发
 

将创建一个新的文件与网址

I have a development and production environment in which my URL's differ:

production:

www.exmaple.com/page

development:

dev.environment/project/page

I know that I can set the base URL in AngularJS with the

<base href='/project/' />

but that doesn't help me out here. Before I load my AngularJS application I fetch a config file (in app.js, with the .run statement, which reads a variable that has the environment:

]).run([
  '$rootScope',
  '$http',
  function (
    $rootScope,
    $http
  ) {
    var configDeferred = $q.defer();

    // fetch config and set the API    
    $http.get('config.json').then(function(response) {
      $rootScope.config = response.data;
      configDeferred.resolve();
    });

    // Wait for the config to be loaded, then go to state
    $rootScope.$on('$stateChangeStart', function (event, next, current) {
      event.preventDefault();
      $q.all([configDeferred.promise]).then(function() {
        $state.transitionTo(next.name);
        return;
      });
    });

Is there a way to dynamically set the base URL, based on a fetched config file in AngularJS (maybe with a .htaccess)?

Attempt 1: Try to get the config via .run and set the base url via ng-href:

Edit the following line of code in my app.js:

// fetch config and set the API    
$http.get('config.json').then(function(response) {
  $rootScope.config = response.data;
  $rootScope.baseUrl = response.data.baseUrl; // '/project/'
  configDeferred.resolve();
});

and in my index.html:

<base ng-href="{{baseUrl}}" />

It looks like this is not working: when I change the href attribute of tag to ng-href, it loads the content correctly, but changes my URL to dev.environment/page instead of dev.environment/project/page

UPDATE: The config file:

{
  "mode": "development",
  "baseUrl": "/project/"
}

解决方案

I personnaly do this kind of stuff with grunt.

When I run my angular-app I have multiple tasks :

> grunt run --target=dev
> grunt run --target=prod
> grunt build --target=dev
> grunt build --target=prod
> etc...

Then grunt do strings replacement with the help of the grunt-preprocess module :

my constants.tpl.js file gets parsed :

[...]
baseUrl:           '/* @echo ENV_WS_URL */',
[...]

and the url is populated.

There are endless possibilities (string replacements, file copy, etc).

Doing it with grunt ensure that dev config files do not go in production for example..

I can put more details if you're interested but I only wanted to show you a different approach.

edit gruntFile example :

'use strict';

module.exports = function(grunt) {

    /**
     * Retrieving current target
     */
    var target = grunt.option('target') || 'dev';
    var availableTargets = [
        'dev',
        'prod'
    ];

    /**
     * Load environment-specific variables
     */
    var envConfig = grunt.file.readJSON('conf.' + target + '.json');

    /**
     * This is the configuration object Grunt uses to give each plugin its
     * instructions.
     */
    grunt.initConfig({
        env: envConfig,       

        /*****************************************/
        /* Build files to a specific env or mode */
        /*****************************************/
        preprocess: {
            options: {
                context: {
                    ENV_WS_URL: '<%= env.wsUrl %>'
                }
            },
            constants: {
                src: 'constants.tpl.js',
                dest: 'constants.js'
            }
        },

        karma: {
            unit: {
                configFile: '<%= src.karma %>',
                autoWatch: false,
                singleRun: true
            },
            watch: {
                configFile: '<%= src.karma %>',
                autoWatch: true,
                singleRun: false
            }
        }

    });


    /****************/
    /* Plugins load */
    /****************/
    grunt.loadNpmTasks('grunt-preprocess');

    /*******************/
    /* Available tasks */
    /*******************/
    grunt.registerTask('run', 'Run task, launch web server for dev part', ['preprocess:constants']);

};

Now, the command :

> grunt run --target=dev

will create a new file with an url

这篇关于如何动态地设置AngularjJS基本URL以获取环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆