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

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

问题描述

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

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

生产:

www.exmaple.com/page

开发:

dev.environment/project/page

我知道我可以使用

但这对我没有帮助.在我加载我的 AngularJS 应用程序之前,我获取了一个配置文件(在 app.js 中,使用 .run 语句,它读取一个具有环境的变量:

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;
      });
    });

有没有办法根据 AngularJS 中提取的配置文件(可能带有 .htaccess)动态设置基本 URL?

尝试 1:尝试通过 .run 获取配置并通过 ng-href 设置基本 URL:

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

在我的 app.js 中编辑以下代码行:

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();
});

在我的 index.html 中:

and in my index.html:

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

看起来这不起作用:当我将标签的 href 属性更改为 ng-href 时,它会正确加载内容,但将我的 URL 更改为 dev.environment/page 而不是 <代码>dev.environment/project/page

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

更新:配置文件:

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

推荐答案

我个人用 grunt 做这种事情.

I personnaly do this kind of stuff with grunt.

当我运行我的 angular-app 时,我有多个任务:

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...

然后 grunt 在 grunt-preprocess 模块的帮助下进行字符串替换:

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

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

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

并填充了 url.

有无限可能(字符串替换、文件复制等).

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

例如使用 grunt 确保开发配置文件不会投入生产..

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.

编辑 gruntFile 示例:

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']);

};

现在,命令:

> grunt run --target=dev

将创建一个带有 url 的新文件

will create a new file with an url

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

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