【问题标题】:In Angularjs how do I load the same javascript file but pass different keys for different environment (Test, beta, prod)在 Angularjs 中,我如何加载相同的 javascript 文件,但为不同的环境(测试、测试版、产品)传递不同的密钥
【发布时间】:2017-04-17 19:32:15
【问题描述】:

在 Angularjs 中的 html 页面中,我需要加载一个外部 javascript 文件:

<script src="https://www.my-url.com/js/my.js?Key=xxxxxxxx"></script>

但是基于不同的环境(测试、测试、产品),我会有不同的 Key。

我怎样才能像我们通常在 .net 中使用 web.config 那样实现它?

编辑:

我看到了一些答案,但似乎不是我所需要的。所以我详细说明了我的环境:我有一个纯 html 和 Angularjs 的客户端,我的服务器端是一个 Asp.net Web API Web 服务。当我在原始帖子中谈论 web.config 时,我并不是说将密钥放在 web.config 中,而是在概念上类似的东西。我想要这个“配置文件”在客户端,而不是我的 Web API。

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您可以使用 gulp-replace 并在构建时自动执行它。

    【讨论】:

    • 这意味着对每个环境进行不同的“构建”,这可能并不理想。不过 Gulp 仍然可以使用。
    • 这取决于您想要承担多少复杂性。为了安全和性能,我也排除了动态加载值。
    • 是的,公平点。我一直试图避免“按环境构建”以确保一致性……测试的是部署的内容。但这并不是说您不能使用 gulp 为环境“准备”应用程序。它确实具有性能优势。
    【解决方案2】:

    有两个问题需要解决:

    1. web.config 值导入 Angular 应用程序
    2. 利用配置下载脚本

    1.将 web.config 获取到应用程序:

    我已经在a blog post 中详细说明了我使用的方法。本质上,在应用程序.cshtml 文件中使用自定义角度提供程序。这将加载前缀为 client: 的所有 web.config 项目...

    由 MVC 控制器使用:

    public static class ApplicationConfiguration
    {
        private const string ClientAppSettingPrefix = "client:";
    
        public static object GetClientConfiguration()
        {
            var clientConfiguration = new ExpandoObject() as IDictionary<string, Object>;
    
            // Find all appSetting entries prefixed with "client:"
            foreach (var key in ConfigurationManager.AppSettings.AllKeys.Where(key => key.StartsWith(ClientAppSettingPrefix)))
            {
                // Remove the "client:" prefix before adding to clientConfiguration
                clientConfiguration.Add(key.Replace(ClientAppSettingPrefix, String.Empty), ConfigurationManager.AppSettings[key]);
            }
    
            return clientConfiguration;
        }
    }
    

    脚本已添加到应用的 .cshtml 文件中:

    <!-- Inject the configuration -->
    <script type="text/javascript">
        (function() {
            angular.module('client.config', [])
                .provider('applicationConfiguration', function() {
                    var config = @Html.Raw(JsonConvert.SerializeObject(Model, new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()}));
                    return {
                        config: config,
                        $get: function() {
                            return config;
                        }
                    };
                });
        })();
    </script>
    

    所以现在您可以在添加时使用它作为普通依赖项:

    angular.module('app', [
        // Add as a dependent module
        'client.config'
      ])
      .config([
            'applicationConfigurationProvider', 'dataServiceProvider', function(applicationConfigurationProvider, dataServiceProvider) {
              // Set the api root server configuration
              dataServiceProvider.setApiRootUrl(applicationConfigurationProvider.config.apiRoot);
            }
      ]);
    

    2。利用config下载脚本

    正如其他答案中所建议的,使用 JQuery 的 getScript() 函数。

    如果您不想依赖 Jquery,其他 SO 答案也建议使用简单的注入 head。看看Single page application - load js file dynamically based on partial view 的想法

    【讨论】:

    • 谢谢。但这并不是我想要的……我想把这个配置放在客户端。我编辑了我的问题。
    • 我明白了。这种方法实际上创建了一个“配置文件”客户端,它只是从服务器的web.config 中设置的值中播种。去掉那部分,加载一个 json 文件听起来更像你正在寻找的东西。
    【解决方案3】:

    这里有几个选项。

    选项 1:

    使用 Angular 的 http 服务以 String 形式动态获取脚本文件,然后使用 eval() 函数执行生成的 String。

    参考:evalAngular $http service

    选项 2:

    使用 JQuery 的 getScript 方法

    例子:

    var keys={ 'prod':'prodKey',
               'staging:='stagingKey',
               'dev':'devKey'
            }
    //Assuming you have an variable storing modes like prod, staging or dev
    var url='https://www.my-url.com/js/my.js?Key='+keys[ENVT.MODE];
    $.getScript( url, function( data, textStatus, jqxhr ) {
        console.log( data ); // Data returned
        console.log( textStatus ); // Success
        console.log( jqxhr.status ); // 200
        console.log( "Script loaded successfully" );
      });
    

    参考:getScript

    【讨论】:

    • 谢谢。你能告诉我更多关于如何做的细节吗?
    • 为 JQuery 方法添加了示例。
    猜你喜欢
    • 1970-01-01
    • 2019-09-12
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多