有两个问题要解决:
- 获取
web.config
值代入角应用
- 利用的配置来获取web.config中下载一个脚本
1.应用程序:
我在a blog post中详细介绍了我使用的方法。实质上,在应用程序.cshtml
文件中使用自定义角度提供程序。这将加载所有web.config
项目,前缀为client:
...
由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()函数。
其他SO的答案也建议使用简单的注入到head
,如果你不想依赖于JQuery。看看Single page application - load js file dynamically based on partial view的想法
这将意味着做一个不同的“建设”每个环境可能不理想。虽然Gulp仍然可以使用。 –
这取决于你想要承担多少复杂性。为了安全和性能,我排除了动态加载值。 – joaofs
是的,公平的一点。我一直试图避免“构建每个环境”的事情来确保一致性......测试的是部署的内容。但这并不是说你不能使用gulp来为应用程序“准备”一个环境。它确实具有性能优势。 –